Printing $0 in different ways - ruby

Among the following ways to print $0, the first one works, yet the second one doesn't. Why?
Directly
puts "current $0 is #{$0}"
Constructing $0 variable name (motivated by javascript)
1.times {|i| puts "current $#{i} is #{$i}"}

Because the second one is looking for a variable called "$i" not "$0"
If you want to build the variable name dynamically you'd need to do something like ...
1.times {|i| puts "current $#{i} is #{eval '$'+i.to_s}"}

Related

how ruby if column less than 4 print column 3?

Im triying to use this code but not work
ruby -a -F';' -ne if $F[2]<4 'puts $F[3]' ppp.txt
this is my file
mmm;2;nsfnjd
sadjjasjnsd;6;gdhjsd
gsduhdssdj;3;gsdhjhjsd
what is doing worng Please help me
First of all, instead of treating Ruby like some kind of fancy Perl and writing scripts like that, let's expand it into the Ruby code equivalent for clarity:
$; = ';'
while gets
$F = $_.split
if $F[2]<4
puts $F[3]
end
end
Your original code doesn't work, it can't possibly work because it's not valid Ruby code, and further, you're not properly quoting it to pass through the -e evaluation term. Trying to run it I get:
-bash: 4: No such file or directory
You're also presuming the array is 1-indexed, but it's not. It's 0-indexed. Additionally Ruby treats integer values as completely different from strings, never equivalent, not auto-converted. As such you need to call .to_i to convert.
Here's a re-written program that does the job:
File.open(ARGV[0]) do |fi|
fi.readlines.each do |line|
parts = line.chomp.split(';')
if parts[1].to_i < 4
puts parts[2]
end
end
end
I solved with this
ruby -a -F';' -ne ' if $F[1] < "4" ;puts $F[2] end ' ppp.txt

Put print result in a variable or concat text variable

I have this
var1='hello'
var2='world'
I need helloworld in a variable. If I write
print $var1$var2 # prints "helloworld"
But when I write
var3=$var1$var2 # var3 is not "helloworld"
I tried
var3=$(print $var1$var2)
var3='$var1$var2'
Sure the only one I did not try is the good one but which one?
Edit after discovery curious thing:
If I do exactly as I wrote
var3=$var1$var2
print $var3 # prints "helloworld"
But in fact I wrote this to resume my problem with others variables, my own variables. The difference is that $var1 is the result of a awk command to extract this text from a file.
I try to explain:
myvar1 the variable I realy use is definite like this:
myvar1=awk -F"/" '${print $1}' $dir_path
And not like this
myvar1=world
That is only to ask you the question. I don't know why, but this seems to be important.
If I do the same thing with my variables that with var3=$var1$var2, it doe snot work. To get the right result with my variables, I have just found I must use:
myvar3=echo$myvar1$myvar2
print $myvar3 # gives the right result.
On the other hand, if I do
var3=echo$var1$var2
print $var3 # prints "echohelloworld"
How to explain that?
I am using Mac OS X, the command-line terminal and Zsh.
If you have
var1='hello'
var2='world'
Any of these will result in print $var3 # prints "helloworld"
var3="$var1$var2"
var4=$var1$var2
var5=$(print $var1$var2)
You should use the first one. You can verify either by printing the variables or by calling set:
$ print var3 # prints "helloworld"
$ set|grep var
var1=hello
var2=world
var3=helloworld
var4=helloworld
var5=helloworld
Your edit says, that you use: myvar1=awk -F"/" '{print $1} $dir_path. This line is missing a $():
myvar1=$(awk 'BEGIN { print "hello" }')
echo $myvar1 # prints hello

How do i create line breaks in ruby?

How would i put line breaks in between lines like this:
print "Hi"
print "Hi"
Because it would just output this:
HiHi
Use puts since it will automatically add a newline for you:
puts "Hi"
puts "Hi"
If you want to make an explicit newline character then you'll need to know what kind of system(s) on which your program will run:
print "Hi\n" # For UNIX-like systems including Mac OS X.
print "Hi\r\n" # For Windows.
Use line break character:
print "Hi\n"
print "Hi"
puts "\n" works also on Win/Ruby ruby 2.4.2p198
and even "\n"*4 for multiplication of new rows (by 4)
You can create a space by adding a string with only a space in it between the 2 other strings. For example:
print "Hi" + " " + "Hi"
You could avoid the two print statements and instead only use one line.
print "Hi\r\nHi"
Or if you want to use two lines then
print "Hi\r\n"
print "Hi"

Ruby 'script = $0'

I was looking at a Ruby script and I came across script = $0. I have done some Googling but I have not found a definite answer as to what this does. I believe that it protects you from reading a file bigger than memory, is that correct?
Thanks, I have the full script below so you can see it in context:
# Takes the name of a file as an argument and assigns to filename
filename = ARGV.first
script = $0
puts "We're going to erase #{filename}."
puts "If you don't want that, hit CTRL-C (^C)."
puts "If you do want that, hit RETURN."
print "? "
STDIN.gets
puts "Opening the file..."
target = File.open(filename, 'w')
puts "Truncating the file. Goodbye!"
target.truncate(target.size)
puts "Now I'm going to ask you for three lines."
print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()
puts "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts "And finally, we close it."
target.close()
$0 is one of Ruby's global variables. From here:
$0 -- Contains the name of the script being executed. May be assignable.
Oh the classic Zed Shaw books! lol
The $0 gets the input on the command line before the first argument. So say you were to run this through the command line using the ruby interpreter you could put "ruby (fileName) test.txt" and $0 will pick up the fileName and save it to the variable 'script'. I'm not really sure why your doing it here because you do use it later in the program, but that's it.
The way you could have tested this would be to print it on the screen using puts, perhaps add this bit of code to see it yourself somewhere in the code:
puts "The $0 has saved #{script} to it, I wonder where it got that."
and see it will name your file.

$1 and \1 in Ruby

When using regular expressions in Ruby, what is the difference between $1 and \1?
\1 is a backreference which will only work in the same sub or gsub method call, e.g.:
"foobar".sub(/foo(.*)/, '\1\1') # => "barbar"
$1 is a global variable which can be used in later code:
if "foobar" =~ /foo(.*)/ then
puts "The matching word was #{$1}"
end
Output:
"The matching word was bar"
# => nil
Keep in mind there's a third option, the block form of sub. Sometimes you need it. Say you want to replace some text with the reverse of that text. You can't use $1 because it's not bound quickly enough:
"foobar".sub(/(.*)/, $1.reverse) # WRONG: either uses a PREVIOUS value of $1,
# or gives an error if $1 is unbound
You also can't use \1, because the sub method just does a simple text-substitution of \1 with the appropriate captured text, there's no magic taking place here:
"foobar".sub(/(.*)/, '\1'.reverse) # WRONG: returns '1\'
So if you want to do anything fancy, you should use the block form of sub ($1, $2, $`, $' etc. will be available):
"foobar".sub(/.*/){|m| m.reverse} # => returns 'raboof'
"foobar".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'

Resources