4

假设我有一个 class Article,这样:

class Article

  attr_accessor :title, :author

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

end

此外,变量atribString包含属性名称的。我怎么能把这个字符串变成一个变量来用作吸气剂?

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

扩展

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

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
4

2 回答 2

6

您可以使用sendinstance_variable_get

a = Article.new 'Asdf', 'Coco'
a.pubic_send(:title) # (Recommended) Tries to call a public method named 'title'. Can raise NoMethodError
=> "Asdf"
# If at rails like your case:
a.try :title # Tries to call 'title' method, returns `nil` if the receiver is `nil` or it does not respond to method 'title'
=> "Asdf"
a.send(:title) # Same, but will work even if the method is private/protected
=> "Asdf"
a.instance_variable_get :@title # Looks for an instance variable, returns nil if one doesn't exist
=> "Asdf"

回答您的扩展问题:不。procs的&: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]
于 2013-10-31T15:13:47.073 回答
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
于 2013-10-31T19:14:20.480 回答