次のような class があると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