This question already has answers here:
What does #{...} mean?
(3 answers)
Closed 8 years ago.
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
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"
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.
Related
I am looking to change the ending of the user name based on the use case (in the language system will operate, names ends depending on how it is used).
So need to define all endings of names and define the replacement for them.
Was suggested to use .gsub regular expression to search and replace in a string:
Changing text based on the final letter of user name
"name surname".gsub(/e\b/, 'ai')
this will replace e with ai, so "name surname = namai surnamai".
How can it be used for more options like: "e = ai, us = mi, i = as" on the same record?
thanks
You can use String#gsub with block. Docs say:
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.
So you can use a regex with concatenation of all substrings to be replaced and then replace it in the block, e.g. using a hash that maps matches to replacements.
Full example:
replacements = {'e'=>'ai', 'us'=>'mi', 'i' => 'as'}
['surname', 'surnamus', 'surnami'].map do |s|
s.gsub(/(e|us|i)$/){|p| replacements[p] }
end
#Sundeep makes an important observation in a comment on the question. If, for example, the substitutions were give by the following hash:
g = {'e'=>'ai', 's'=>'es', 'us'=>'mi', 'i' => 'as'}
#=> {"e"=>"ai", "s"=>"es", "us"=>"mi", "i"=>"as"}
'surnamus' would be converted (incorrectly) to 'surnamues' merely because 's'=>'es' precedes 'us'=>'mi' in g. That situation may not exist at present, but it may be prudent to allow for it in future, particularly because it is so simple to do so:
h = g.sort_by { |k,_| -k.size }.to_h
#=> {"us"=>"mi", "e"=>"ai", "s"=>"es", "i"=>"as"}
arr = ['surname', 'surnamus', 'surnami', 'surnamo']
The substitutions can be done using the form of String##sub that employs a hash as its second argument.
r = /#{Regexp.union(h.keys)}\z/
#=> /(?-mix:us|e|s|i)\z/i
arr.map { |s| s.sub(r,h) }
#=> ["surnamai", "surnammi", "surnamas", "surnamo"]
See also Regexp::union.
Incidentally, though key-insertion order has been guaranteed for hashes since Ruby v1.9, there is a continuing debate as to whether that property should be made use of in Ruby code, mainly because there was no concept of key order when hashes were first used in computer programs. This answer provides a good example of the benefit of exploiting key order.
How do I store Ruby standard outputs to multiple variables?
For example, if I have:
puts "hello"
puts "thanks"
How do I store "hello" and "thanks" to two different variables like strVar (containing the value "hello") and strVar2 (containing the value "thanks").
In my script, I am calling another Ruby script which will puts multiple strings to standard output. How do I store each string from the standard output individually?
I'm not sure that I understand the question, but there are countless numbers of ways to store / print strings. Its hard to imagine a situation where you would have a value following puts that is not entered manually or set programatically.
You can save input variables with gets or $stdin.gets or as an argument with the ARGV array. For example:
puts "Enter the first string"
var0 = $stdin.gets.chomp
If you already have the values saved
var1 = "hello"
var2 = "thanks"
array = [var1, var2]
hash = {:key1 => var1, :key2 => var2}
puts var1
puts var2
array.each do |str| puts str end
hash.map do |k, v| puts v end
You're basically chaining applications/scripts together. There are multiple ways to do it but the simplest path uses the STDIN/STDOUT pipeline.
A simple example would be using two small scripts. Save this as test.rb:
puts 'foo'
puts 'bar'
and this as test2.rb:
v1 = gets.chomp
v2 = gets.chomp
puts "v1=#{v1} v2=#{v2}"
then, at the command line use:
ruby test.rb | ruby test2.rb
which will output:
v1=foo v2=bar
| is how we chain the output of one script to the input of another and isn't part of Ruby, it's part of the OS.
This works because, by default, puts writes to STDOUT and gets reads from STDIN. | wires them together.
I am trying to set an email address within ActionMailer with Rails. Before it was hard coded, but we want to make them ENV variables now so we don't need to amend code each time an email changes.
Here is how it's currently defined:
from = '"Name of Person" <email#email.com>'
I've tried setting the email as an environment variable using ENV['EMAIL'] but I'm having no luck even with #{ENV['EMAIL'}.
Can anyone point me in the right direction?
You cannot use string interpolation with single-quoted strings in Ruby.
But double-quoted strings can!
from = "'Name of Person' <#{ENV['EMAIL']}>"
But if you want to keep your double-quotes wrapping the Name of Person, you can escape them with a backslash \:
from = "\"Name of Person\" <#{ENV['EMAIL']}>"
Or use string concatenation:
from = '"Name of Person" <' + ENV['EMAIL'] + '>'
# but I find it ugly
If you want to embed double quotes in an interpolated string you can use % notation delimiters (which Ruby stole from Perl), e.g.
from = %|"Name of Person", <#{ENV['EMAIL']}>|
or
from = %("Name of Person", <#{ENV['EMAIL']}>)
Just pick a delimiter after the % that isn't already in your string.
You can also use format. I have not seen it used as commonly in Ruby as in other languages (e.g. C, Python), but it works just as well:
from = format('"Name of Person", <%s>', ENV["EMAIL"])
Alternative syntax using the % operator:
from = '"Name of Person", <%s>' % ENV["EMAIL"]
Here is the documentation for format (aka sprintf):
http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-format
This question already has an answer here:
Anyone can comment this ruby code? [closed]
(1 answer)
Closed 8 years ago.
I don't know ruby language. I was reading a very interesting article which contain a following 2 line ruby code which i need to understand.
(0..0xFFFFFFFFFF).each do |i|
puts "#{"%010x" % i}"
end
By googling, i get the 1st line. But i am not able to understand 2nd line. Can someone please explain its meaning?
puts "#{"%010x" % i}" has actually two parts - string interpolation (which G.B tells you about), and string format using %:
Format—Uses str as a format specification, and returns the result of
applying it to arg. If the format specification contains more than one
substitution, then arg must be an Array or Hash containing the values
to be substituted. See Kernel::sprintf for details of the format
string.
"%05d" % 123 #=> "00123"
"%-5s: %08x" % [ "ID", self.object_id ] #=> "ID : 200e14d6"
"foo = %{foo}" % { :foo => 'bar' } #=> "foo = bar"
So "%010x" % i formats the integer in hex format (x) with at least 10 digits (10), padding with zeros (the leading 0):
"%010x" % 150000
# => "00000249f0"
Actually
puts "#{"%010x" % i}"
is exactly the same as
puts "%010x" % i
since the interpolation simply puts the resulting value (a string) within a string....
Puts key word is used to print the data on the console.
for example
puts "writing data to console"
above line will print exact line to the console "writing data to console"
#a = "this is a string"
puts #a
this will print "this is a test string"
puts "My variable a contains #{#a}"
this will print "My variable a contains this is a string" and this merging technique is called string interpolation.
this first argument in puts "#{"%010x" % i}" specifies the format and second represents the value.
and for your exact question and further details see this link
it's string interpolation and sprintf
documents:
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Interpolation
http://www.ruby-doc.org/core-2.1.2/Kernel.html#method-i-sprintf
http://batsov.com/articles/2013/06/27/the-elements-of-style-in-ruby-number-2-favor-sprintf-format-over-string-number-percent/
"%010x" % i is same as sprintf("%010x", i)
puts "#{"%010x" % i}"
This line print the content. and if you want o interpolated the string please used single quote inside the double quote. like this "#{'%010x' % i }"
and %x means convert integer into hexadecimal and %010x means make it 10 place value means if out is 0 then make it like this 0000000000.
Print
puts is the equivalent of echo in PHP and printf in C
When included in either a command-line app, or as part of a larger application, it basically allows you to output the text you assign to the method:
puts "#{"%010x" % i}"
This will basically print the contents of "#{"%010x" % i}" on the screen - the content of which means that ruby will output the calculaton of what's inside the curly braces (which has been explained in another answer)
I have confusion for using expression interpolation in method. Initially I thought I can pass any kind of expression like let's say name.capitalize, but I can pass without expression interpolation too. Here is the two cases. Just execute below two methods on irb, I have same result for both method. I am using Ruby 1.9.3
1.
def say_goodnight(name)
result = "Good night, " + name.capitalize
return result
end
puts say_goodnight('uncle')
2.
def say_goodnight(name)
result = "Good night, #{name.capitalize}"
return result
end
puts say_goodnight('uncle')
Both way it will produce output like
Good night, Uncle
So my question is When Should I use expression interpolation in Ruby? and When Should I use parameter in Ruby?
Whichever reads cleaner is generally better. For example, if the string contains a number of variable references, each separated by a few characters, the "+" form of the expression can become complex and unclear, while an interpolated string is more obvious. On the other hand, if the expression(s) are relatively complex, it's better to separate them from other components of the string.
So, I think the following:
"Hello #{yourname}, my name is #{myname} and I'm #{mood} to see you."
is clearer than
"Hello " + yourname + ", my name is " + myname + " and I'm " + mood + "to see you."
But if I had complex expressions, I might want to separate those onto different source code lines, and those are better connected with "+".
I'm with #djconnel–use whichever reads the best, communicates the most information, eases modification and/or extension, makes debugging simple, and so on.
This was just discussed yesterday; see Strange Ruby Syntax?
In your specific example, I'd use string interpolation, because the method is really just:
def say_goodnight(name)
"Good night, #{name.capitalize}"
end