Ruby's for
keyword is an anti pattern! In fact, it's actually slower than each
and uses each
in the background.
for n in [1, 2, 3, 4]
puts n
end
[1, 2, 3, 4].each do |n|
puts n
end
Map is useful when you need to change every value in an Enumerable
.
doubles = []
[1, 2, 3, 4].each do |n|
doubles << n * 2
end
[1, 2, 3, 4].map do |n|
n * 2
end
Reduce is useful when you want to gradually create a value based on each element in an Enumerable.
sum = 0
[1, 2, 3, 4].each do |n|
sum += n
end
sum
[1, 2, 3, 4].reduce(0) do |sum, n|
sum + n
end
This is similar to reduce
, except you don't have to explicitly return a new value for the accumulator.
words = ['one', 'two', 'two', 'three', 'three', 'three']
words.reduce(Hash.new(0)) do |occurrences, str|
occurrences[str] += 1
occurrences
end
words = ['one', 'two', 'two', 'three', 'three', 'three']
words.each_with_object(Hash.new(0)) do |str, occurrences|
occurrences[str] += 1
end
all?
is handy for checking if each element in an Enumerable
meet a given condition.
all_odd = true
[1, 2, 3].each |n|
if n.even?
all_odd = false
break
end
end
[1, 2, 3].all? |n|
n.odd?
end
any?
is handy for checking if there is any element in an Enumerable
that meets a given condition.
any_even = false
[1, 2, 3].each |n|
any_even = true if n.even?
end
[1, 2, 3].any? |n|
n.even?
end