Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 597
Hamish Downer Avatar asked Apr 24 '09 15:04

Hamish Downer


People also ask

Is Getattr slow python?

Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.

Is Getattr fast?

The getattr approach is slower than the if approach, reducing an insignificant ~3% the performance if bar is set and a considerable~35% if is not set.


1 Answers

The equivalent statement in Ruby:

date_wanted = :created_on
title_date = list_titles.send(date_wanted)
like image 86
Matt Haley Avatar answered Sep 22 '22 23:09

Matt Haley