timpone
timpone

Reputation: 19929

interpolating a string to part of a ruby method

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

Upvotes: 3

Views: 933

Answers (2)

Mars
Mars

Reputation: 1528

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.

Upvotes: -1

oldergod
oldergod

Reputation: 15000

Use send

item = Item.find(id)

if item.send(:"is_#{type}") == true
  item.send(:"is_#{type}=", false)
end 

Upvotes: 6

Related Questions