gpt4 book ai didi

ruby-on-rails - Ruby/Rails 将字符串转换为类属性

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:58 25 4
gpt4 key购买 nike

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

class Article

attr_accessor :title, :author

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

end

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

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

最佳答案

您可以使用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]

关于ruby-on-rails - Ruby/Rails 将字符串转换为类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com