ruby-on-railsrubylanguage-comparisons

What is the ruby equivalent of python's getattr


I am new to rails and trying to do a little refactoring (putting a partial renderer that lists titles in app/views/shared ) The renderer shows the dates along with the titles. However different users of the renderer use different dates. Part way through refactoring I have

title_date = list_titles.created_on

For the other user of the renderer I would want

title_date = list_titles.updated_on

So can I use a string I pass through (using the :locals parameter)? I know in Python I could do

date_wanted = 'created_on'
title_date = getattr(list_titles, date_wanted)

but I can't work out how to do that in ruby. (Obviously in rails I would pass the date_wanted string through from the view calling the partial renderer.)


Solution

  • The equivalent statement in Ruby:

    date_wanted = :created_on
    title_date = list_titles.send(date_wanted)