How do I store standard outputs to multiple variables? - ruby-on-rails

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.

Related

concatenate two values ruby

i'm trying to map one value to other, following is my code
what im trying to do is call one api and get that values and pass to another api and map both values in the end, i get the values from both apis but failing to concatenate. how to solve this?
response = conn.get("/api/vhosts")
statistics = JSON.parse(response.body)
statistics.each do |vhosts|
# puts "vhostname: #{vhosts["name"]}"
response1 = conn.get("/api/aliveness-test/#{vhosts["name"]}")
statistics1 = JSON.parse(response1.body)
puts "#{vhosts["name"]} " + statistics1.fetch('status', :unknown)
end
end
Preferably, concatenate string using << is a little more faster and performatic:
puts "#{vhosts["name"]} " << statistics1.fetch('status', :unknown).to_s
The error is telling that you are trying to concatenate a string and a symbol. So, one of the two parts is a symbol, not a string. You have some options.
puts "#{vhosts["name"]} #{statistics1.fetch('status', :unknown)}"
or
puts "#{vhosts["name"]} " + statistics1.fetch('status', :unknown).to_s

Can't understand "puts" keyword in Ruby code [duplicate]

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)

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.

How do I read each line of uploaded file with mixed Windows and Unix line endings?

I am trying to read each line of an uploaded file in Rails.
file_data = params[:files]
if file_data.respond_to?(:read)
file_data.read.gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
inputUsers.push(line.strip)
end
elsif file_data.respond_to?(:path)
File.read(file_data.path).gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
inputUsers.push(line.strip)
end
If the uploaded file contains a mix of Windows and Unix encodings, presumably being due to copying from multiple places, Rails doesn't properly seperate each line of the file and sometimes returns two lines as one.
The application is hosted on a Linux box. Also, the file is copied from a Google docs spreadsheet column.
Are there any solutions for this problem?
Edit:
Hex code for lines that don't get seperated into new lines look like:
636f 6d0d 0a4e 6968
Here's how I'd go about this. First, to test some code:
SAMPLE_TEXT = [
"now\ris\r\nthe\ntime\n",
"for all good men\n"
]
def read_file(data)
data.each do |li|
[ *li.split(/[\r\n]+/) ].each do |l|
yield l
end
end
end
read_file(SAMPLE_TEXT) do |li|
puts li
end
Which outputs:
now
is
the
time
for all good men
The magic occurs in [ *li.split(/[\r\n]+/) ]. Breaking it down:
li.split(/[\r\n]+/) causes the line to be split on returns, new-lines and combinations of those. If a line has multiples the code will gobble empty lines, so if there's a chance you'll receive those you'll need a little more sophisticated pattern, /[\r\n]{1,2}/ which, though untested, should work.
*li.split(/[\r\n]+/) uses the "splat" operator * which says to explode the following array into its component elements. This is a convenient way to get an array when you're not sure whether you have a single element or an array being passed into a method.
[*li.split(/[\r\n]+/)] takes the components returned and turns them back into a single array.
To modify the method to handle a file instead is easy:
def read_file(fname)
File.foreach(fname) do |li|
[ *li.split(/[\r\n]+/) ].each do |l|
yield l
end
end
end
Call it almost the same way as in the previous example:
read_file('path/to/file') do |li|
puts li
end
The reason you want to use foreach is it'll read line-by-line, which is a lot more memory efficient than slurping a file using read or readlines, either of which read the entire file into memory at once. foreach is extremely fast also, so you don't take a speed-hit when using it. As a result there's little advantage to read-type methods, and good advantages to using foreach.
You are substituting \n with \r\n, which is problematic when parsing Windows files. Now \r\n becomes \r\r\n.
Better is to substitute to the Unix line ending format and then split on \n:
file_data.read.gsub( /\n/, "\r\n" ).split("\r\n").each do |line|
becomes:
file_data.read.gsub( /\r\n/, "\n" ).split("\n").each do |line|
Try the built-in method:
File.readlines('foo').each do |line|
Or:
File.open('foo').read.gsub(/\r\n?/, "\n").each_line do |line|

How do I escape #{ from string interpolation

I have a heredoc where I am using #{} to interpolate some other strings, but there is an instance where I also want to write the actual text #{some_ruby_stuff} in my heredoc, WITHOUT it being interpolated. Is there a way to escape the #{.
I've tried "\", but no luck. Although it escapes the #{}, it also includes the "\":
>> <<-END
#{RAILS_ENV} \#{RAILS_ENV}
END
=> " development \#{RAILS_ENV}\n"
For heredoc without having to hand-escape all your potential interpolations, you can use single-quote-style-heredoc. It works like this:
item = <<-'END'
#{code} stuff
whatever i want to say #{here}
END
I think the backslash-hash is just Ruby being helpful in some irb-only way.
>> a,b = 1,2 #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s #=> 1 #{b}
>> s.size #=> 6
So I think you already have the correct answer.
You can use ' quotes instead. Anything enclosed in them is not being interpolated.
Your solution with escaping # also works for me. Indeed Ruby interpreter shows
=> "\#{anything}"
but
> puts "\#{anything}"
#{anything}
=> nil
Your string includes exactly what you wanted, only p method shows it with escape characters. Actually, p method shows you, how string should be written to get exactly object represented by its parameter.

Resources