Pergunta

I a trying to follow a tutorial with Ruby, but am getting very confused. Everywhere I find seems to say that defining an instance variable is done like so;

class Example
  def fun
    # CODE
  end
end

e = Example.new
e.fun     # <- Will run your code

Bu I really really don't get why this isn't working

class Example
  include Enumerable

  def initialise
    @members = ["a", "b"]
  end

  def each
    @members.each do |member|
      yield member
    end
  end

end

When I call

e = Example.new

e.each do |elmt|
  puts elmt
end

I get the error

NoMethodError: undefined method `each' for nil:NilClass

Can anybody help me figure out how to get this working. I cant find out what's wrong, below are 3 of the many sources that lead me to believe this should work. I am obviously doing something wrong, but I just cant see it

sources; http://ruby.about.com/od/advancedruby/ss/Using-The-Enumerable-Module.htm http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/ Book: Engineering Software as a Service

Foi útil?

Solução

You have a typo. It's initialize, not initialise. Your @members instance var was never assigned to, that's why it's nil.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top