3

I have items that can be one of several attributes like red, yellow, green (more complex than this) and they have corresponding is_red, is_yellow, is_green booleans.

I'd like to have an api function to change this value where I pass for example:

id: 12
type: red

in my function have:

item=Item.find(id)
if item.is_ + type == true
  item.is_ + type=false
end 

How would I do this?

thx in advance

5
  • 2
    Don't. Have a single attribute called Color and a method is_color(color) instead. Commented Oct 2, 2012 at 1:00
  • thx, as mentioned in question, it is more complex than just colors (in fact doesn't involve colors). Commented Oct 2, 2012 at 1:02
  • 1
    I can't think of a single use case where this would be a good idea, even not involving colors. Commented Oct 2, 2012 at 1:18
  • legacy system with well constructed graphs of data. works really well Commented Oct 2, 2012 at 1:39
  • The question states "variable names" bit the example code references method calls. Commented Oct 2, 2012 at 5:42

2 Answers 2

6

Use send

item = Item.find(id)

if item.send(:"is_#{type}") == true
  item.send(:"is_#{type}=", false)
end 
Sign up to request clarification or add additional context in comments.

1 Comment

Send will take either a string or a symbol, so the colons could be omitted if desired.
-1

You cannot build variable names dynamically in Ruby without using eval, which would be dirty, but functional.

You could use method_missing on a BlankSlate object to capture free text method calls and handle them as a big dirty case statement.

The most elegant solution would be a Hash, because keys can be easily composed dynamically.

Comments

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.