How could I display a text on the same line? - ruby

I accept text input from a user. When I use the received text within a line as follows,
puts "whats your name?"
$name = STDIN.gets
puts "Oh #$name, nice to meet you"
it is displayed on a separate line. It puts the name and then the "nice to meet you" on a new line.
Is there a way to fix this? Also if you see something wrong, please tell me.

The method gets without any option receives the input including the terminating end of line. If you simply interpolate that as a part of a string, that end of line will be printed as a line break.
To avoid line break, pass the parameter chomp with value true to gets:
$name = STDIN.gets(chomp: true)
In the old school way, apply chomp after gets like:
$name = STDIN.gets.chomp
chomp removes white space characters from the end of the string, thus it avoids the line break.
Other things wrong about your code are:
You missed to capitalize the sentence whats your name?.
You missed an apostrophe in whats.
You should avoid using a global variable like $name. Try using another type of variable.
You missed a period at the end of the sentence Oh #$name, nice to meet you.

I would suggest changing that global variable to a local variable. If you do, you'll have to change the way you interpolate.
Also, I would suggest using the gets.chomp method and leave out STDIN.
Example:
puts "What's your name?"
name = gets.chomp
puts "Oh, #{name}, nice to meet you."

gets is used to input data from the user and includes a line break at the end.
chomp is used to return and store data as a string value.
$name = STDIN.gets.chomp

Related

'gets' doesn't wait for user input

I'm attempting to develop a program on repl.it using its Ruby platform. Here's what I've got:
puts "Copy the entire request page and paste it into this console, then
hit ENTER."
request_info = gets("Edit Confirmation").chomp.gsub!(/\s+/m, '
').strip.split(" ")
puts "What is your name?"
your_name = gets.chomp
puts "Thanks, #{your_name}!"
The way I've got it, the user pastes a multi-line request, which ends with "Edit Confirmation", and then it splits the request, word-by-word, into its own array for me to parse and pull the relevant data.
But I can't seem to use the gets command a second time after initially inquiring the user for a multi-line input at the start. Any other gets command I attempt to use after that is skipped, and the program ends.
Your code is doing something quite unusual: By passing a string to the gets method, you are actually changing the input separator:
gets(sep, limit [, getline_args]) → string or nil
Reads the next “line'' from the I/O stream; lines are separated by sep.
The reason why your code is not working as you expect is because a trailing "\n" character is left in the input buffer - so calling gets a second time instantly returns this string.
Perhaps the easiest way to resolve this would just be to absorb this character in the first gets call:
request_info = gets("Edit Confirmation\n").chomp.gsub!(/\s+/m, ' ').strip.split(" ")
For a "complex" multi-line input like this, it would be more common to pass a file name parameter to the ruby script, and read this file rather than pasting it into the terminal.
Or, you could use gets(nil) to read until an EOF character and ask the user to press CTRL+D to signify the end of the multi-line input.

Why strings are not coming in same line in ruby

In this code in three places i am having puts, Where first one prints variables in different line with the string and second one too. but 3rd one gives in same line.
def calliee (name,game)
#puts("#{name}#{game} he might be a bad guy")
return " he might be a bad guy #{name}#{game}"
end
def mymethod(name)
puts("enter your last name")
ss=gets()
#return "#{name}"+"#{ss}"+"he might be a bad guy"
calliee(name,ss)
end
puts("enter tour first name")
tt=gets()
#ww=mymethod(tt)
yy=mymethod(tt)
puts(yy)
puts("#{tt} is 1st name")
puts("prabhu "+"#{2+3}"+"#{4+5}")
i want everything in same line and i need to know why this is happening. please help
Kernel#gets gives you a string with the \n added to the end of the string. That causing the output in the multiple lines.
To make your output as you wanted it to be, you need to use #chomp method, like gets.chomp.
Adding to Arup's answer:
puts adds a newline to the end of the output. print does not. So you may also want to replace puts with print to have all output in one line.

Stop getting input with gets when specific character, similar chomp

In ruby I can stop getting inputs with:
name = gets.chomp
puts "Hello my name is " + name
How can I stop getting the input when a user types in END.
For example:
I hate it to write END
The input is terminated by the new line character that the user inputs. On standard console, you cannot terminate the input in other ways.
If you really want to do that introducing some heavy mechanism, then you should use curses, and particularly use getch.
How about
puts while gets.chomp != "END"

.downcase! syntax shorthand

Can someone explain what the difference is between the two pieces of code below? Both feature an ! at the end. Is the first version just the shorthand?
print "Who are you?"
user_input = gets.chomp.downcase!
print "Who are you?"
user_input = gets.chomp
user_input.downcase!
Edit: Having an exclamation point (aka "bang") at the end of a method name in ruby means "handle with care". From Matz himself:
The bang (!) does not mean "destructive" nor lack of it mean non
destructive either. The bang sign means "the bang version is more
dangerous than its non bang counterpart; handle with care". Since
Ruby has a lot of "destructive" methods, if bang signs follow your
opinion, every Ruby program would be full of bangs, thus ugly.
(For the full thread, see #sawa's link in the comments.)
For the method in question, downcase is making a copy of the given string, modifying that, and returning that copy as a result. Whereas downcase! modifies the string itself.
In the first case, you're modifying the variable stored in gets.chomp, in the second you're modifying user_input.
Note that if you call user_input.downcase on the last line (instead of user_input.downcase!) it won't actually change user_input, it just returns a copy of the string and makes the copy lowercase.

Why does Ruby's 'gets' includes the closing newline?

I never need the ending newline I get from gets. Half of the time I forget to chomp it and it is a pain in the....
Why is it there?
Like puts (which sounds similar), it is designed to work with lines, using the \n character.
gets takes an optional argument that is used for "splitting" the input (or "just reading till it arrives). It defaults to the special global variable $/, which contains a \n by default.
gets is a pretty generic method for readings streams and includes this separator. If it would not do it, parts of the stream content would be lost.
var = gets.chomp
This puts it all on one line for you.
If you look at the documentation of IO#gets, you'll notice that the method takes an optional parameter sep which defaults to $/ (the input record separator). You can decide to split input on other things than newlines, e.g. paragraphs ("a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs)"):
>> gets('')
dsfasdf
fasfds
dsafadsf #=> "dsfasdf\nfasfds\n\n"
From a performance perspective, the better question would be "why should I get rid of it?". It's not a big cost, but under the hood you have to pay to chomp the string being returned. While you may never have had a case where you need it, you've surely had plenty of cases where you don't care -- gets s; puts stuff() if s =~ /y/i, etc. In those cases, you'll see a (tiny, tiny) performance improvement by not chomping.
How I auto-detect line endings:
# file open in binary mode
line_ending = 13.chr + 10.chr
check = file.read(1000)
case check
when /\r\n/
# already set
when /\n/
line_ending = 10.chr
when /\r/
line_ending = 13.chr
end
file.rewind
while !file.eof?
line = file.gets(line_ending).chomp
...
end

Resources