What does the "yield" keyword do in Ruby? -


i encountered following ruby code:

class myclass     attr_accessor :items     ...     def each         @items.each{|item| yield item}     end     ... end 

what each method do? in particular, don't understand yield does.

this example fleshing out sample code:

class myclass   attr_accessor :items    def initialize(ary=[])     @items = ary   end    def each     @items.each |item|        yield item     end   end end  my_class = myclass.new(%w[a b c d]) my_class.each |y|   puts y end # >> # >> b # >> c # >> d 

each loops on collection. in case it's looping on each item in @items array, initialized/created when did new(%w[a b c d]) statement.

yield item in myclass.each method passes item block attached my_class.each. item being yielded assigned local y.

does help?

now, here's bit more how each works. using same class definition, here's code:

my_class = myclass.new(%w[a b c d])  # points `each` enumerator/method of @items array in instance via #  accessor defined, not method "each" you've defined. my_class_iterator = my_class.items.each # => #<enumerator: ["a", "b", "c", "d"]:each>  # next item on array my_class_iterator.next # => "a"  # next item on array my_class_iterator.next # => "b"  # next item on array my_class_iterator.next # => "c"  # next item on array my_class_iterator.next # => "d"  # next item on array my_class_iterator.next # =>  # ~> -:21:in `next': iteration reached end (stopiteration) # ~>    -:21:in `<main>' 

notice on last next iterator fell off end of array. potential pitfall not using block because if don't know how many elements in array can ask many items , exception.

using each block iterate on @items receiver , stop when reaches last item, avoiding error, , keeping things nice , clean.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -