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
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."
Am Samstag, 02. Jan 2010, 21:20:02 +0900 schrieb Ruby Newbee:
> 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
--
Bertram Scharpf
Stuttgart, Deutschland/Germany
*
Support `String#notempty?': <http://raa.ruby-lang.org/project/step>.
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.
--
Posted via http://www.ruby-forum.com/.
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.