Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

can't understand for this each

0 views
Skip to first unread message

Ruby Newbee

unread,
Jan 2, 2010, 7:20:02 AM1/2/10
to
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

Josh Cheek

unread,
Jan 2, 2010, 8:05:24 AM1/2/10
to
[Note: parts of this message were removed to make it a legal post.]

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

Bertram Scharpf

unread,
Jan 2, 2010, 8:48:11 AM1/2/10
to
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


--
Bertram Scharpf
Stuttgart, Deutschland/Germany
*
Support `String#notempty?': <http://raa.ruby-lang.org/project/step>.

Brian Candler

unread,
Jan 2, 2010, 1:36:29 PM1/2/10
to
Ruby Newbee 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.
--
Posted via http://www.ruby-forum.com/.

Ruby Newbee

unread,
Jan 2, 2010, 10:12:43 PM1/2/10
to
On Sun, Jan 3, 2010 at 2:36 AM, Brian Candler <b.ca...@pobox.com> wrote:
> Ruby Newbee 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.

0 new messages