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

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

···

On Sat, Jan 2, 2010 at 6:20 AM, Ruby Newbee <rubynewbee@gmail.com> wrote:

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

Hi,

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
<Programming Ruby: The Pragmatic Programmer's Guide.

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

···

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

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

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/\.

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.

···

On Sun, Jan 3, 2010 at 2:36 AM, Brian Candler <b.candler@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" ?