can't understand for this each

R

Ruby Newbee

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
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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
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."
 
B

Bertram Scharpf

Hi,

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
 
B

Brian Candler

Ruby said:
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.
 
R

Ruby Newbee

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top