Why doesn't puts() print in a single line? - ruby

This is a piece of code:
def add(a, b)
a + b;
end
print "Tell number 1 : "
number1 = gets.to_f
print "and number 2 : "
number2 = gets.to_f
puts "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
When I run it, my results are spread over several lines:
C:\Users\Filip>ruby ext1.rb
Tell number 1 : 2
and number 2 : 3
3.0+3.0 =
5.0
C:\Users\Filip>
Why doesn't puts() print in a single line, and how can keep the output on one line?

gets() includes the newline. Replace it with gets.strip. (Update: You updated your code, so if you're happy working with floats, this is no longer relevant.)
puts() adds a newline for each argument that doesn't already end in a newline. Your code is equivalent to:
print "#{number1}+#{number2} = ", "\n",
add(number1, number2) , "\n",
"\n"
You can replace puts with print:
print "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
or better:
puts "#{number1}+#{number2} = #{add(number1, number2)}"

Because puts prints a string followed by a newline. If you do not want newlines, use print instead.

Puts adds a newline to the end of the output. Print does not. Try print.
http://ruby-doc.org/core-2.0/IO.html#method-i-puts
You might also want to replace gets with gets.chomp.
puts "After entering something, you can see the the 'New Line': "
a = gets
print a
puts "After entering something, you can't see the the 'New Line': "
a = gets.chomp
print a

Related

Reverse a string while keeping it in a single line

I'm trying to reverse a string using the code:
puts("Hi now it's going to be done!")
string = gets.chomp.to_s
i = string.length
while i >= 0
puts(string[i])
i = i - 1
end
It prints the string in backward order, but each word is on a single line. How can I keep all of them on a single line?
puts adds a newline to the end of the output if one isn't already present.
print does not. So do this:
while i >=0
print string[i]
i=i-1
end
puts
The final puts is because you want any further printing to be on a new line.
Try this:
"Hi now it's going to be done!".chars.inject([]) { |s, c| s.unshift(c) }.join
Or This is a little easier to follow:
string = 'Hi now it's going to be done!'
string.reverse!

Unambigous behaviour during print in Ruby

The print statement given below executes correctly when I remove the parentheses and produces an error syntax error, unexpected ',', expecting ')' when parentheses are kept. Any help would be appreciated since I am new to Ruby
print "Enter name: "
name=gets
puts name
puts "Enter first number"
num1=gets
puts "Enter Second number"
num2=gets
result=Integer(num1)+Integer(num2)
print ("The addition of "+num1.chomp+" and " + num2.chomp+ " is ",result)
There are several ways to achieve what you want:
get rid of the space between print and (
print("The addition of " + num1.chomp + " and " + num2.chomp + " is ", result)
use + to concatenate the strings; this will require you to use to_s to convert the numeric value result into a string:
print("The addition of " + num1.chomp + " and " + num2.chomp + " is " + result.to_s)
use string interpolation:
print("The addition of #{num1.chomp} and #{num2.chomp} is #{result}")
Do you have a Python background? This code looks like Python written in Ruby ;)
print 'Enter first number: '
num1 = gets.to_i
print 'Enter Second number: '
num2 = gets.to_i
puts format('The addition of %d and %d is %d', num1, num2, num1 + num2)
String#to_i is more often used than Integer(). Also, both Integer() and to_i ignore newlines, so you don't need to call chomp.
Kernel#format is a good and fast way to integrate variables in a string. It uses the same format as C/Python/Java/...
print "Enter name: "
name=gets.strip ##strip method removes unnecessary spaces from start & End
puts "Enter first number"
num1=gets.strip.to_i ##convert string number into Int
puts "Enter Second number"
num2=gets.strip.to_i
result=num1+num2
print "The addition: #{num1} + #{num2} = #{result}" ##String interpolation.

Combine more than one \flags in Ruby regex (\A, \w)

I try to catch only cases b and d from sample below (ie. END should be the only word on a line (or at least be a word not part of longer word, and END should be at beginning of line (not necessarily ^, could start from column #2, case \i.)
I cannot combine this all togethernin one regex, can I have more then 1 flag in regex? I also need this OR in this regex too.
Thanks all.
M
regexDrop = /String01|String2|\AEND/i #END\n/i
a = "the long END not begin of line"
b = "ENd" # <#><< need this one
c = "END MORE WORDs"
d =" EnD" # <#><< need this one
if a =~ regexDrop then puts "a__Match: " + a else puts 'a_' end
if b =~ regexDrop then puts "b__Match: " + b else puts 'b_' end
if c =~ regexDrop then puts "c__Match: " + c else puts 'c_' end
if d =~ regexDrop then puts "d__Match: " + d else puts 'd_' end
## \w Matches word characters.
## \A Matches beginning of string. (could be not column 1)
Note that \A is an anchor (a kind of a built-in lookehind, or "zero width assertion", that matches the beginning of a whole string. The \w is a shorthand class matching letters, digits and an underscore (word characters).
Judging by your description and sample input and expected output, I think you are just looking for END anywhere in a string as a whole word and case-insensitive.
You can match the instances with
regexDrop = /String01|String2|\bEND\b/i
Here is a demo
Output:
a__Match: the long END not begin of line
b__Match: ENd
c__Match: END MORE WORDs
d__Match: EnD

Ruby Console: How to Keep 'gets' from adding a new line when the user inputs

Why does gets always add a new line when the user inputs the number of boxes?
I want the next print statement to be shown on the same line as the input.
print "Enter the number of boxes: "
boxes = gets.chomp
print "Enter number of columns to print the boxes in: "
columns = gets.chomp
I want output to look like this:
Enter the number of boxes: 47 Enter number of columns to print the boxes in: 4
I don't want to begin a new line until after the second input is received.
You'll need to use IO/console and build up your input a character at a time:
require 'io/console'
def cgets(stream=$stdin)
$stdin.echo = false
s = ""
while true do
c = stream.getc
return s if c == "\n"
s << c
end
end
The issue is echoing the input back; getting the character out when it isn't a newline is a bit problematic (at least locally, not on my regular machine). Also, since you're getting the characters manually, it removes normal readline functionality, so behavior will be system-dependent e.g., Unixy systems might lose their backspace etc.
That said, yuck; IMO on the console this is an unexpected UI pattern, and keeping the input on two lines is more obvious, and more common.
In windows you can do it like this, otherwise you would need a similar read_char method that works in your OS
def read_char #only on windows
require "Win32API"
Win32API.new("crtdll", "_getch", [], "L").Call
end
def get_number
number, inp = "", 0
while inp != 13
inp = read_char
if "0123456789"[inp.chr]
number += inp.chr
print inp.chr
end
end
number
end
print "Enter the number of boxes: "
boxes = get_number
print " Enter number of columns to print the boxes in: "
columns = get_number
puts ""
puts "boxes: #{boxes}"
puts "columns: #{columns}"
# gives
# Enter the number of boxes: 5 Enter number of columns to print the boxes in: 6
# boxes: 5
# columns: 6

How to overwrite a printed line in the shell with Ruby?

How would I overwrite the previously printed line in a Unix shell with Ruby?
Say I'd like to output the current time on a shell every second, but instead of stacking down each time string, I'd like to overwrite the previously displayed time.
You can use the \r escape sequence at the end of the line (the next line will overwrite this line). Following your example:
require 'time'
loop do
time = Time.now.to_s + "\r"
print time
$stdout.flush
sleep 1
end
Use the escape sequence \r at the end of the line - it is a carriage return without a line feed.
On most unix terminals this will do what you want: the next line will overwrite the previous line.
You may want to pad the end of your lines with spaces if they are shorter than the previous lines.
Note that this is not Ruby-specific. This trick works in any language!
Here is an example I just wrote up that takes an Array and outputs whitespace if needed. You can uncomment the speed variable to control the speed at runtime. Also remove the other sleep 0.2 The last part in the array must be blank to output the entire array, still working on fixing it.
##speed = ARGV[0]
strArray = [ "First String there are also things here to backspace", "Second Stringhereare other things too ahdafadsf", "Third String", "Forth String", "Fifth String", "Sixth String", " " ]
#array = [ "/", "-", "|", "|", "-", "\\", " "]
def makeNewLine(array)
diff = nil
print array[0], "\r"
for i in (1..array.count - 1)
#sleep #speed.to_f
sleep 0.2
if array[i].length < array[i - 1].length
diff = array[i - 1].length - array[i].length
end
print array[i]
diff.times { print " " } if !diff.nil?
print "\r"
$stdout.flush
end
end
20.times { makeNewLine(strArray) }
#20.times { makeNewLine(array)}
Following this answer for bash, I've made this method:
def overwrite(text, lines_back = 1)
erase_lines = "\033[1A\033[0K" * lines_back
system("echo \"\r#{erase_lines}#{text}\"")
end
which can be used like this:
def print_some_stuff
print("Only\n")
sleep(1)
overwrite("one")
sleep(1)
overwrite("line")
sleep(1)
overwrite("multiple\nlines")
sleep(1)
overwrite("this\ntime", 2)
end
You can use
Ruby module curses, which was part of the Ruby standard library
Cursor Movement
puts "Old line"
puts "\e[1A\e[Knew line"
See also Overwrite last line on terminal:

Resources