Reputation: 759
How would I select a specific attribute based on user input?
For example, say I have the following Object table, with attributes 'name', 'shape', 'color'. I'm trying to be able to select an attribute based on user input. If the user enters '1', for example, it should return the value of the first attribute, 'name'.
Is there a way to do this without hard coding all the options with if statements like in the following? I have 28 attributes for my object, so doing all these if statements seems excessive.
if userInput == '1'
return @object.name
end
Upvotes: 0
Views: 647
Reputation: 146053
I have to think that this is not a good way to achieve your actual objective, but to answer the question you asked:
return @object.send @object.attribute_names[userInput.to_i]
Or perhaps:
@object.send %w{fieldname anotherfield yetanotherfieldname}[userInput.to_i]
Or perhaps:
@object.attributes.values[userInput.to_i]
Upvotes: 1