Suppose I have a class Article, such that:
class Article
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author= author
end
end
Also, variable atrib is a String containing the name of an attribute. How could I turn this string into a variable to use as a getter?
a = Article.new
atrib='title'
puts a.eval(atrib) # <---- I want to do this
EXTENDED
Suppose I now have an Array of articles, and I want to sort them by title. Is there a way to do the compact version using & as in:
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
a.send(atrib.to_sym)to_symis not actually required a string is acceptable as well so you could calla.send(atrib)a.title.. ?ActiveRecord?