2012-05-29 64 views
0

考虑下面的代码:字符串到对象?

我收到一个对象从包含从我选择值的DataMapper:

user = User.first() 
puts user.name 
# John 
puts user.surname 
# Doe 
puts user.age 
# 42 

在用户定义的数组我必须要显示

dataordering = ["age", "surname", "name"] 
这些值订单

那么,如何获得我的数组中排序的值?

dataordering.each do |sequence| 
    puts user.sequence 
    # this, of course, fails 
end 

我不想使用eval()。不。

也许还有更好的方法来存储值的排序?

回答

1

你可以选择从记录的值是这样的:

user_attributes = user.attributes 

dataordering.each do |attribute| 
    puts user_attributes[attribute.to_sym] 
end 

或者使用send方法:

dataordering.each do |attribute| 
    puts user.send attribute.to_sym 
end 

作为排序的解决方案,我可以为您提供这样的代码:

dataordering.map { |attr| user.send attribute.to_sym } 
+0

非常感谢。属性方法与to_sym结合起来了! – witsches