views:

122

answers:

1

Alright. So I have a table called contacts. In this table I have people and there contact information and how their preferred method of contact (Phone, Address, Email, or Fax). I want to be able to have ruby output a list of said people in a manner I could copy paste into a email address bar or such.

<% @contacts.each do |contact| %>
      <%=h contact.contact_name %> < <%=h contact.preferred_method %> >,
<% end %>

This works, but it doesn't do what I want it to do and I didn't expect it to. So for a list of people whos preferred choice is email it outputs the list as.

Mike < Email >, Joe < Email >, John < Address >, Sarah < Phone >

instead of

Mike <[email protected]>, Joe <[email protected]>, John <2014 Street>, Sarah <111-111-1111>

It's calling the preferred_method, but what I actually want it to do is...

<% @contacts.each do |contact| %>
      <%=h contact.contact_name %> < <%=h contact.<%=h contact.preferred_method %> >,
<% end %>

So I would get contact.address or contact.phone depending on their preferred_method. But obviously that doesn't work. So I thought of trying to assign <%=h contact.preferred_method %> to a varible.

x = contact.preferred_method

And then have

<% @contacts.each do |contact| %>
      <%=h contact.contact_name %> < <%=h contact.x %> >,
<% end %>

but that doesn't work either.

Any help would be appreciated.

Mike

+2  A: 

You can use the send method.

<%=h contact.send(contact.preferred_method.downcase) %>

Invokes the method identified by a symbol or string on the receiving object.

contact.send(:email) 
contact.send('address')

Note I set a downcase on the contact.preferred_method because I assume your method name is 'email' not 'Email'

Corban Brook