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
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]
精彩评论