Ruby undefined method 'each' for class -


i getting error when create class of stats , container class. error

test.rb:43:in `<main>' undefined method `each' #<boyfriends:0x2803db8 @boyfriends=[, , , ]> (nomethoderror) 

which makes absolute sense because class indeed not contain method, should ruby search parents , grandparents classes method? script displays desired output; inlays error output so

test.rb:43:in `<main>'i love rikuo because 8 years old , has 13 inch nose love dolar because 12 years old , has 18 inch nose love ghot because 53 years old , has 0 inch nose love grats because unknown years old , has 9999 inch nose : undefined method `each' #<boyfriends:0x2803db8 @boyfriends=[, , , ]> (nomethoderror) 

here code

class boyfriends     def initialize         @boyfriends = array.new     end      def append(aboyfriend)         @boyfriends.push(aboyfriend)         self     end      def deletefirst         @boyfriends.shift     end      def deletelast         @boyfriends.pop     end      def [](key)         return @boyfriends[key] if key.kind_of?(integer)         return @boyfriends.find { |aboyfriend| aboyfriend.name }     end end  class boyfriendstats     def initialize(name, age, nose_size)         @name = name         @age = age         @nose_size = nose_size     end      def to_s         puts "i love #{@name} because #{@age} years old , has #{@nose_size} inch nose"     end      attr_reader :name, :age, :nose_size     attr_writer :name, :age, :nose_size end  list = boyfriends.new list.append(boyfriendstats.new("rikuo", 8, 13)).append(boyfriendstats.new("dolar", 12, 18)).append(boyfriendstats.new("ghot", 53, 0)).append(boyfriendstats.new("grats", "unknown", 9999))  list.each { |boyfriend| boyfriend.to_s } 

which makes absolute sense because class indeed not contain method, i've been reading should ruby search classes parents , grandparents method?

that's correct, didn't declare superclasses superclass object. doesn't have each method.

if want enumerable method, you'll have define - you'll want iterate on array.

in case, define own each method passes passed block down arrays each method:

class boyfriends    def each(&block)      @boyfriends.each(&block)    end end 

the &block here let's capture passed block name. if you're new ruby, doesn't mean you, , explaining how works beyond scope of question. accepted answer in this question pretty job of explaining how blocks , yield work.

once got each method, can pull in enumerable number of convenience methods:

class boyfriends     include enumerable end 

also, to_s method should return string, should remove puts in boyfriendstats#to_s.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -