0

I'm trying to define a method in a model to simplify things I'm doing in my controller as below:

models/game.rb

def build_array_for(words)
  words.downcase.split(",")
end

I'm calling the method in the controller as below

games_controller.rb

@wordsArray = @game.build_array_for(red_words)

Note that 'red_words' is an attribute of instances of Game which value is supposed to be a string

When I call the method I get:

undefined local variable or method `red_words' for GamesController

If I build the method as:

def build_array
  red_words.downcase.split(",")
end

it works but since I'm using it with other attributes for the same purpose it wouldn't make sense.

What am I missing here, could it be that the argument is passed as a string and for some reason the name of the attribute is not recognised?

2 Answers 2

4

If you need build array for existed column then you can try this:

def build_array_for(column)
  self[column].downcase.split(",")
end

If you want build array for any instance variable when:

def build_array_for(name)
  self.send(name).downcase.split(",")
end

Use symbol or string for a parameter:

@wordsArray = @game.build_array_for(:red_words)
Sign up to request clarification or add additional context in comments.

3 Comments

No luck Alex, both alternatives derive in the same error
Call it like this @wordsArray = @game.build_array_for(:red_words)
That's great Alex it works great now. Thanks a lot for your help!
0

Change the method to

def build_array_for(words)
  words.downcase.split(",")
end

When you are using self rails will try to find an attribute words or instance method words for Game object

EDIT

Make this changes accordingly

games_controller.rb

@wordsArray = @game.build_array_for(red_words)

models/game.rb

def build_array(red_words)
  red_words.downcase.split(",")
end

5 Comments

The result is the same. I think in Ruby it's the same using 'self' or not? In both cases is trying to find an instance method that takes the value of the parameter 'words' for the Game object. In both cases I get "undefined local variable or method `red_words' "
If its not an attribute or an association you must pass it as parameter
make sure you are passing the params with method call and accepting the params in method
Yes, I tried without 'self' as your code above before. However, I'm getting the same error (I'll take out 'self' from question to not confuse).
Not sure that I follow your train of thought. 'red_words' is definitely an attribute of instances of Game, if I call @game.red_words it all works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.