How to re-write specific Ruby code in Elixir

I’m busy learning Elixir and I’m struggling to transform the below Ruby code into Elixir.

list = [12, 12, 45, 12, 16]
counts = Hash.new(0)
list.each { |elem| counts[elem] += 1 }
return counts
# => {12 => 3, 16 => 1, 45 => 1 }`

Essentially I’m trying to find how many times a certain number occurs in an elixir char list
and then return a map.

This is my first post on the forum so if I’ve done anything unconventional please steer me in the right direction :smile:

Thanks

2 Likes

You’ll want to have a look at Enum.reduce/3 for such tasks. Here’s one solution:

Enum.reduce(list, %{}, &Map.update(&2, &1, 1, fn x -> x + 1 end))

8 Likes

One important thing to note is that unlike Ruby’s Hash, Elixir’s Map(%{}) does not allow specifying a custom value to be returned when nothing is found. Rather, when retrieving a value, use Map.get(mymap, key, default) and specify the default value (0 in this case) there.

5 Likes

Thank you, this worked perfectly. I will definitely dive deeper into understanding the Enum module as well as the capture operator.

3 Likes

Yep! That will help you even in your ruby projects! The Enum module on elixir is almost the same as the Enumerable module in ruby :slight_smile:

2 Likes