Can't understand "puts" keyword in Ruby code [duplicate] - ruby-on-rails

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)

Related

How do I store standard outputs to multiple variables?

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.

Lua: Quoted arguments passed as one in function

I'm attempting to simplify a script, and my attempts are failing. I'm making a function that will pass the given arguments and turn them into an indexed table, but I want to be able to pass quoted and non-quoted alike and have the function recognize that quoted arguments are considered one value while also respecting non-quoted arguments.
For example:
makelist dog "brown mouse" cat tiger "colorful parrot"
should return an indexed table like the following:
list_table = {"dog", "brown mouse", "cat", "tiger", "colorful parrot"}
The code I have works for quoted, but it's messing up on the non-quoted, and on top of that, adds the quoted arguments a second time. Here's what I have:
function makelist(str)
require 'tprint'
local list_table = {}
for word in string.gmatch(str, '%b""') do
table.insert(list_table, word)
end
for word in string.gmatch(str, '[^%p](%a+)[^%p]') do
table.insert(list_table, word)
end
tprint(list_table)
end
I'm not understanding why the omission of quotes is being ignored, and also is chopping off the first letter. That is, this is the output I receive from tprint (a function that prints a table out, not relevant to the code):
makelist('dog "brown mouse" cat tiger "colorful parrot"')
1=""brown mouse""
2=""colorful parrot""
3="og"
4="rown"
5="mouse"
6="cat"
7="tiger"
8="olorful"
9="parrot"
As you can see, 'd', 'b', and 'c' are missing. What fixes do I need to make so that I can get the following output instead?
1="brown mouse"
2="colorful parrot"
3="dog"
4="cat"
5="tiger"
Or better yet, have them retain the same order they were dictated as arguments, if that's possible at all.
local function makelist(str)
local t = {}
for quoted, non_quoted in ('""'..str):gmatch'(%b"")([^"]*)' do
table.insert(t, quoted ~= '""' and quoted:sub(2,-2) or nil)
for word in non_quoted:gmatch'%S+' do
table.insert(t, word)
end
end
return t
end
It may be easier to simply split on whitespaces and concatenate those elements that are inside quotes. Something like this may work (I added few more test cases):
function makelist(str)
local params, quoted = {}, false
for sep, word in str:gmatch("(%s*)(%S+)") do
local word, oquote = word:gsub('^"', "") -- check opening quote
local word, cquote = word:gsub('"$', "") -- check closing quote
-- flip open/close quotes when inside quoted string
if quoted then -- if already quoted, then concatenate
params[#params] = params[#params]..sep..word
else -- otherwise, add a new element to the list
params[#params+1] = word
end
if quoted and word == "" then oquote, cquote = 0, oquote end
quoted = (quoted or (oquote > 0)) and not (cquote > 0)
end
return params
end
local list = makelist([[
dog "brown mouse" cat tiger " colorful parrot " "quoted"
in"quoted "terminated by space " " space started" next "unbalanced
]])
for k, v in ipairs(list) do print(k, v) end
This prints the following list for me:
1 dog
2 brown mouse
3 cat
4 tiger
5 colorful parrot
6 quoted
7 in"quoted
8 terminated by space
9 space started
10 next
11 unbalanced
First thanks for your question, got me to learn the basics of Lua!
Second, so I think you went with your solution in a bit of misdirection. Looking at the question I just said why don't you split once by the quotes (") and than choose where you want to split by space.
This is what I came up with:
function makelist(str)
local list_table = {}
i=0
in_quotes = 1
if str:sub(0,1) == '"' then
in_quotes = 0
end
for section in string.gmatch(str, '[^"]+') do
i = i + 1
if (i % 2) == in_quotes then
for word in string.gmatch(section, '[^ ]+') do
table.insert(list_table, word)
end
else
table.insert(list_table, section)
end
end
for key,value in pairs(list_table) do print(key,value) end
end
The result:
1 dog
2 brown mouse
3 cat
4 tiger
5 colorful parrot

What does #{ } mean in Ruby? [duplicate]

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.

What does % do in the following code?

I'm reading The "Rails 3 Way" and on page 39, it shows a code sample of the match :to => redirect method. In that method the following code exists. Whilst I know what modulo does with numbers, I'm unsure what the % is doing below because both path and params are clearly not numbers. If anyone can help me understand the use of % in this situation, I'd appreciate it.
proc { |params| path % params }
That's probably the String#% method which works a lot like sprintf does in other languages:
'%05d' % 10
# => "00010"
It can take either a single argument or an array:
'%.3f %s' % [ 10.341412, 'samples' ]
# => "10.341 samples"
Update: As Philip points out, this method also takes a hash:
'%{count} %{label}' % { count: 20, label: 'samples' }
# => "20 samples"
Of course, this is presuming that path is a String. In Ruby you never really know for sure unless you carefully read the code. It's unlikely, but it could be % meaning modulo.
The thing you can be sure of is it's calling method % on path.
It does string interpolation. In the simplest case, it's equivalent to:
"foo %s baz" % 'bar'
#=> "foo bar baz"
However, you can use more complex format specifiers to interpolate from Array or Hash objects too, such as the Rails params hash. See the String#% and Kernel#sprintf methods for details on how to construct a valid format specification.

How can I replace new lines with \n character

Data stored in the database is like this:
This is a line
This is another line
How about this line
When I output it to the view, I want to convert that to:
This is a line\n\nThis is another line\n\nHow about this line
with no new lines and the actual \n characters printed out. How can I do that?
> s = "hi\nthere"
> puts s
hi
there
> puts s.gsub(/\n/, "\\n")
hi\nthere
I would personally use gsub if you only want newlines specifically converted. However, if you want to generally inspect the contents of the string, do this:
str = "This is a line\n\nThis is another line\n\nHow about this line"
puts str.inspect[1..-2]
#=> This is a line\n\nThis is another line\n\nHow about this line
The String#inspect method escapes various 'control' characters in your string. It also wraps the string with ", which I've stripped off above. Note that this may produce undesirable results, e.g. the string My name is "Phrogz" will come out as My name is \"Phrogz\".
> s = "line 1\n\nline2"
=> "line 1\n\nline2"
> puts s
line 1
line2
> puts s.gsub("\n", "\\n")
line 1\n\nline2
The key is to escape the single backslash.

Resources