2008年4月30日 星期三

each, each_with_index, map

each:

accept block parameter that describe what to do with each element of array or hash


ex: 

[“A”, “B”].each do |i|

       puts “#{i}”

end

--->  A

        B


each_index:

ex:

["A", "B"].each_index do |i|
    puts "#{i}"
end

each_with_index:

ex:

['a','b','c'].each_with_index do |content, index|

puts "#{content}#{index}"

end

---> a0

       b1

       c2


map:

v.s each: different in return 

it return the new value, each return original value

ex:

[1,2,3].map{ |i| i*2 }

--->[2,4,6]

map! will change content of caller


沒有留言: