Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 663
timpone Avatar asked Sep 09 '26 20:09

timpone


1 Answers

Use send

item = Item.find(id)

if item.send(:"is_#{type}") == true
  item.send(:"is_#{type}=", false)
end 
like image 80
oldergod Avatar answered Sep 12 '26 22:09

oldergod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!