Stop getting input with gets when specific character, similar chomp - ruby

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"

Related

How could I display a text on the same line?

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

'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.

Difference between ways to use gets method

I saw two ways to use gets, a simple form:
print 'Insert your name: '
name = gets()
puts "Your name is #{name}"
and a form that drew my attention:
print 'Insert your name: '
STDOUT.flush
name = gets.chomp
puts "Your name is #{name}"
The second sample looks like perl in using the flush method of the default output stream. Perl makes explicit default output stream manipulating; the method flush is a mystery to me. It can behave different from what I'm inferring, and it uses chomp to remove the new line character.
What happens behind the scenes in the second form? What situation is it useful or necessary to use the second form?
"Flushing" the output ensures that it shows the printed message before it waits for your input; this may be just someone being certain unnecessarily, or it may be that on certain operating systems you need it. Alternatively you can use STDOUT.sync = true to force a flush after every output. (You may wonder, "Why wouldn't I always use this?" Well, if your code is outputting a lot of content, repeatedly flushing it may slow it down.)
chomp removes the newline from the end of the input. If you want the newline (the result of the user pressing "Enter" after typing their name) then don't chomp it.
Looking at some Github code I can see that STDOUT.flush is used mostly for server-side/multi-threaded jobs, and not in everyday use.
Generally speaking, when you want to accept input from the user, you'd want to use gets.chomp. Just remember, no matter what the user enters, Ruby will ALWAYS interprete that as a string.
To convert it to an integer, you need to call to_i, or to_f for a float. You don't need chomp in these cases, since to_i or to_f removes the "\n" automatically. There are a lot of subtle things going on implicitly as you'll see, and figuring them out is simply a matter of practice.
I've rarely seen someone use STDOUT.flush except in mutli-threading. Also it makes things confusing, defeating the whole purpose of writing elegant code.

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