Exploring tally, group_by, and transform_values methods in Ruby.
tally Method:
The tally
method is available in Ruby 2.7 or later versions.
It is used to count the occurrences of elements in an enumerable object and returns a hash with the elements as keys and their respective counts as values.
arr = [1, 2, 3, 2, 1, 1, 3, 4, 5, 4, 3]
=> [1, 2, 3, 2, 1, 1, 3, 4, 5, 4, 3]
arr.tally # here we get the value as a count of the value
=> {1=>3, 2=>2, 3=>3, 4=>2, 5=>1}
group_by Method:
The group_by
method is a built-in Ruby method available on enumerable objects.
It groups the elements based on a given block and returns a hash where the keys are the grouping criteria and the values are arrays containing the elements that match each criterion.
arr = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
arr.group_by {|num| num%2}
=> {1=>[1, 3, 5], 0=>[2, 4]}
transform_values Method:
The transform_values
method is available in Ruby 2.4 or later versions.
It is used to transform the values of a hash based on a given block and returns a new hash with the transformed values.
hash = { a: 1, b: 2, c: 3 }
=> {:a=>1, :b=>2, :c=>3}
result = hash.transform_values { |value| value * 2 }
=> {:a=>2, :b=>4, :c=>6}