lundi 27 juillet 2015

pipe blocks (|x,y|) in ruby methods [duplicate]

This question already has an answer here:

I'm very new to ruby, and still fairly novice to OOP languages in general so I apologize in advance if this question is poorly worded. I've noticed a pattern in ruby methods where the first argument is a block and within that block is something like |x,y| I noticed it first in the .each method

@some_hash.each do |key, value|
    puts "#{key} => #{value}"
end

my understanding of do and end is that they are just like any other block in ruby, so in theory the code above could be written like so

test_hash.each {|k,v| puts "#{k} => #{v}"}

Sure enough this also works. So my question is what's actually happening under the hood here? What is the .each method doing with this block and how to the values k and v get assigned? How could I write a method that would do something similar?

Aucun commentaire:

Enregistrer un commentaire