0

I've been trying to show random images everytime a user post something. I have images name "kejang (#).png" # ranging from 1 to 21.

So I have done this.

<div class = 'article_header'>
    <div class = 'article_img'>
        <% kj_num = rand(20) + 1 %>
        <%= kj_num %>
        <%= image_tag 'kejang (#{kj_num}).PNG' %>
    </div>

It does run on the server but returns no image, only 'x' marked crashed images.

I wondered where it went wrong and altered #{kj_num} with regular number and it worked. (i.e, I put 2 or 3 instead of #{kj_num} and it worked.)

Why is #{kj_num} not working ?? Rails interpretting #{variable} as a simple text. How should I change my code?

zebralamy
  • 313
  • 1
  • 4
  • 14

2 Answers2

2

#{} vs. single vs. double quotes

Here you need to use double quotes (") rather than single quotes (')

<div class = 'article_header'>
    <div class = 'article_img'>
        <% kj_num = rand(20) + 1 %>
        <%= kj_num %>
        <%= image_tag "kejang (#{kj_num}).PNG" %>
    </div>
</div>

String interpolation is the process of converting placeholders inside a string to the values they represent, in order to produce a dynamic string. You probably use it all the time without realizing just how cool it works under the hood, and how you can leverage this power in your own classes.

person = 'World'
puts "Hello, #{person}!" 

https://kconrails.com/2010/12/08/ruby-string-interpolation/

Vishwas Nahar
  • 418
  • 7
  • 21
  • 1
    Thank you so much for the super fast answer. I was really stuck and I was frustrated and I desperately came to Stackoverflow. The answer was posted soooo fast and it just solved my problem in a second. Thanks man. – zebralamy Apr 09 '17 at 11:17
0

You are trying to use string interpolation inside single quotes which will not work. You have to use double quotes instead

Here is an example to understand it,

jruby-1.7.13 :001 > name  = 'ajinkya'
=> "ajinkya"
jruby-1.7.13 :002 > 'hello, #{name}'
=> "hello, \#{name}"
jruby-1.7.13 :003 > "hello, #{name}"
=> "hello, ajinkya"

More detailed explanation about Double vs single quotes

Community
  • 1
  • 1
Ajinkya Pisal
  • 551
  • 1
  • 6
  • 24