Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails - Variable inside a Variable
    text
    copied!<p>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. </p> <pre><code>&lt;% @contacts.each do |contact| %&gt; &lt;%=h contact.contact_name %&gt; &lt; &lt;%=h contact.preferred_method %&gt; &gt;, &lt;% end %&gt; </code></pre> <p>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.</p> <p>Mike &lt; Email >, Joe &lt; Email >, John &lt; Address >, Sarah &lt; Phone ></p> <p>instead of</p> <pre><code>Mike &lt;mike@yahoo.com&gt;, Joe &lt;joe@aol.com&gt;, John &lt;2014 Street&gt;, Sarah &lt;111-111-1111&gt; </code></pre> <p>It's calling the preferred_method, but what I actually want it to do is...</p> <pre><code>&lt;% @contacts.each do |contact| %&gt; &lt;%=h contact.contact_name %&gt; &lt; &lt;%=h contact.&lt;%=h contact.preferred_method %&gt; &gt;, &lt;% end %&gt; </code></pre> <p>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 <code>&lt;%=h contact.preferred_method %&gt;</code> to a variable.</p> <pre><code>x = contact.preferred_method </code></pre> <p>And then have</p> <pre><code>&lt;% @contacts.each do |contact| %&gt; &lt;%=h contact.contact_name %&gt; &lt; &lt;%=h contact.x %&gt; &gt;, &lt;% end %&gt; </code></pre> <p>but that doesn't work either.</p> <p>Any help would be appreciated.</p> <p>Mike</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload