1
votes

I am facing a undefined local variable or method error when initializing the following in ruby:

 class Model
  attr_accessor :var1, :var2, :state
  def initialize (x, y, key)
    @var1 = x
    @var2 = y
    @state = every_state[:key] #this line produces the error

  @every_state = {
  :A => SateA.new,
  :B => StateB.new,
  :C => StateC.new,
  :D => StateD.new
  }       
  end

  def select_state(key)
    every_state[:key]
  end
end

When I am using the class like

model = Model.new(1,2,:A)

The error occurs: undefined local variable or method `every_state'

As I am new to ruby coming from a java background, I wanted to pass a key to the initialize method (as noted here), to select a specific initial state from the hash.

Could it be that I am using the hash in a wrong way, or should I take it out of the initialize method completely and use another method to set it? My other thought is that I am using the symbol for key incorrectly.

Also, is there a direct implication of operating on non-instance variables within the initialize method? For example I was wondering what is the purpose of declaring the hash as an instance variable within initialize...

Any ideas are very welcome.

3
Your indentation is wrong - @every_state is defined in #initialize, and thus should be indented at the same level. Also, you should initialize @every_state before using it - move the initialization before the call (@state = ...) - hrnt

3 Answers

2
votes

You don't have a function called "every_state". You only have a instance variable @every_state. That is why you get an error.

Replace all calls to every_state with @every_state. You don't have a function or a local variable every_state. You only have a instance variable @every_state.

1
votes

I believe this implementation is the closest one to the Java one.

class Model
  attr_accessor :var1, :var2, :state

  def initialize (x, y, key)
    @var1 = x
    @var2 = y
    @every_state = {
      :A => SataeA.new,
      :B => StateB.new,
      :C => StateC.new,
      :D => StateD.new
    }   
    @state = select_state key 
  end

  def select_state(key)
    @every_state[key]
  end
end
1
votes

you have a typo: :A => SateA.new should be :A => StateA.new. Also I would put the hash definition at the top level outside of the initialize method otherwise you'll be redefining it with every call to new which is definite;y NOT want you want to do!