Ruby / Rails将字符串转换为类属性

时间:2013-10-31 15:09:58

标签: ruby-on-rails ruby

假设我有一个班级Article,这样:

class Article

  attr_accessor :title, :author

  def initialize(title, author)
    @title = title
    @author= author
  end

end

此外,变量atrib是包含属性名称的String。如何将此字符串转换为变量以用作吸气剂?

a = Article.new
atrib='title'
puts a.eval(atrib)     # <---- I want to do this

扩展

假设我现在有Array篇文章,我想按标题对它们进行排序。有没有办法使用&执行紧凑版本,如:

col = Article[0..10]
sorted_one = col.sort_by{|a| a.try('title') }   #This works
sorted_two = col.sort_by(&:try('title'))   #This does not work

2 个答案:

答案 0 :(得分:4)

您可以使用sendinstance_variable_get

a = Article.new 'Asdf', 'Coco'
a.send(:title) # Tries to call method named 'title'. Can raise NoMethodError
=> "Asdf"
a.instance_variable_get :@title # Looks for an instance variable, returns nil if one doesn't exist
=> "Asdf"
# If at rails like your case:
a.try :title # "Tries" to call 'title' method, returns nil if the receiver, `a` in this case, is nil
=> "Asdf"

回答你的扩展问题:不。 proc的&:symbol快捷方式依赖于Symbol#to_proc方法。因此,要启用该行为,您需要在Symbol类上重新设置该方法,顺便说一下,这是我一直关注的功能,所以......:

class Symbol
  def to_proc  
    ->(x) { x.instance_eval(self.to_s) }    
  end  
end

[1,2,3].map(&:"to_s.to_i * 10")
=> [10, 20, 30]

答案 1 :(得分:1)

ActiveRecord个实例有一个attributes哈希:

a = Article.new(title: 'foo')
#=> <#Article id: nil, title: "foo">

atrib = 'title'
a.attributes[atrib]
#=> "foo"

您可以使用order从数据库中获取已排序的对象:

Article.order('title').first(10)
#=> array of first 10 articles ordered by title