Pregunta

I know that this may be a very basic question but i'm struggling to find a clear answer. What does using this, #{} , mean in Ruby? What does it do?

Thanks

¿Fue útil?

Solución

It is used for String interpolation: ( wikipedia, ctrl+f "ruby" )

apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}

The output will be:

I have 4 apples

String interpolation, Definition:

In Ruby, string interpolation refers to the ability of double-quoted strings to execute Ruby code and replace portions of that strings (denoted by #{ ... }) with the evaluation of that Ruby code.

It is the most common way to inject data (usually the value of a variable, but it can be the evaluation of any Ruby code) into the middle of a string.


A thing to know:

puts "This User name is #{User.create(username: 'Bobby')}!"

This will make an implicit call of .to_s on the User's instance object.

If you defined the method .to_s on the User model:

class User
  def to_s
    self.username
  end

It would output:

puts "This User name is #{User.create(username: 'Bobby')}"
# => "This User name is Bobby"

Otros consejos

It is for String Interpolation..

In Ruby, there are three ways of interpolation, and #{} is just one way.

apples = 4
puts "I have #{apples} apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}

It's called String Interpolation

In Ruby, string interpolation refers to the ability of double-quoted strings to execute Ruby code and replace portions of that strings (denoted by #{ ... }) with the evaluation of that Ruby code. It is the most common way to inject data (usually the value of a variable, but it can be the evaluation of any Ruby code) into the middle of a string.

print "What is your name? "
name = gets.chomp
puts "Hello, #{name}"

Note that any code can go inside the braces, not just variable names. Ruby will evaluate that code and whatever is returned it will attempt to insert it into the string. So you could just as easily say "Hello, #{gets.chomp}" and forget about the name variable. However, it's good practice not to put long expressions inside the braces.

Author: Michael Morin

That allows you to evaluate arbitrary ruby code within a string (double quotes only). So for example, in something like PHP you'd do

$my_var = "The value of a = " . $a;

But in ruby, you'd just do

my_var = "The value of a = #{a}"

This only works if the string is in double quotes, and NOT single quotes. If you us single quotes then you'll get the #{...} appear in the text

You use it to represent a variable you want to print or puts out. For example:

puts "#{var}" would puts out the value stored within your variable var.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top