Ruby/Array/each

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Arrays and Blocks

# each lets you iterate over every element in an array and do something to it. 
month_a = %w[ nil jan feb mar apr may jun jul aug sep oct nov dec ] 
month_a.each { |e| print e.capitalize + " " }



Assign block value to a variable in array each method

data = ["1", "2", "3"]
s = ""
data.each { |x| s << x << " and a "}



each with block which has if statement

[1,2,3].each {|i| puts i}
# 1
# 2
# 3
[1,2,3].each do |i|
  if i % 2 == 0
    puts "#{i} is even."
  else
    puts "#{i} is odd."
  end
end
# 1 is odd.
# 2 is even.
# 3 is odd.



Iterating Over an Array with each

[1, 2, 3, 4].each { |x| puts x }
# 1
# 2
# 3
# 4



LocalJumpError: no block given

p [1, 2, 3].each