Can't understand for this each

Hello,

Please take a look at below.
what’s each{ … } in the find_all method?
I can’t understand for it. thanks.

class Hash
def find_all
new_hash = Hash.new
each { |k,v| new_hash[k] = v if yield(k, v) }
new_hash
end
end

squares = {0=>0, 1=>1, 2=>4, 3=>9}
z=squares.find_all { |key, value| key > 1 }
p z

On Sat, Jan 2, 2010 at 6:20 AM, Ruby N. [email protected]
wrote:

new_hash
end
end

squares = {0=>0, 1=>1, 2=>4, 3=>9}
z=squares.find_all { |key, value| key > 1 }
p z

An English translation might read “For each key value pair in the hash,
add
it to the new hash if the block submitted returns true.”

Hi,

Am Samstag, 02. Jan 2010, 21:20:02 +0900 schrieb Ruby N.:

what’s each{ … } in the find_all method?

class Hash
def find_all
new_hash = Hash.new
each { |k,v| new_hash[k] = v if yield(k, v) }
new_hash
end
end

Hash#each' is not Array#each’. It is descibed in
http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_hash.html#Hash.each.

It does something like

class Hash
def each
keys.each { |k|
yield k, self[ k]
}
end
end

A remarkable aspect is that `Hash#each’ yields two values so that
everywhere in Enumerable’s descriptions “{ |obj| … }” has to be
replaced with “{ |k,v| … }” or even “|(k,v)|”. For example, you
have to call

hash.each_with_index { |(k,v),i| … }

Bertram

On Sun, Jan 3, 2010 at 2:36 AM, Brian C. [email protected]
wrote:

Ruby N. wrote:

Hello,

Please take a look at below.
what’s each{ … } in the find_all method?
I can’t understand for it. thanks.

Would it help if you think of it as “self.each” ?

oops that’s right.
I know what’s each.
But I don’t understand for a raw each there…
yes self.each, got it, thanks!

Jenn.

Ruby N. wrote:

Hello,

Please take a look at below.
what’s each{ … } in the find_all method?
I can’t understand for it. thanks.

Would it help if you think of it as “self.each” ?

That is, you are calling the method called “each” on the current object
instance, which in this case is a Hash.