vint-i-vuit vint-i-vuit - 1 year ago 43
Ruby Question

Ruby/Rails convert string to a class attribute

Suppose I have a class

, such that:

class Article

attr_accessor :title, :author

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


Also, variable
is a
containing the name of an attribute. How could I turn this string into a variable to use as a getter?

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


Suppose I now have an
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

Answer Source

You can use either send or instance_variable_get:

a = '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"

Shot answer to your extended question: no. The &:symbol shortcut for procs relies on Symbol#to_proc method. So to enable that behavior you'd need to redifine that method on the Symbol class, which by the way, is a feature I always looked up to, so...:

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

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