Okay, so when I do code like:
puts "Hallo: "
response = gets.chomp
What I want is the user to see something like this:
Hallo: _
(With the underscore being the text input area) But instead, they see something more like this
Hallo:
_
Is there a way to fix this?
Like Sergio said you need to use print instead of puts, the difference is that print outputs the raw version without any modifications. Puts on the other hand adds a newline at the end.
puts 'Hallo: " is the same as print "Hallo: \n"
Related
I'm currently in the process of learning ruby, and I don't know if I'm doing something wrong or the compiler is, but this code:
puts "Name?"
name = gets
puts "Welcome " + name
Outputs:
#blank line waiting for input, if gotten input
Prints input, Name? And Welcome Name
I want it to do something like python's input("Name? ")
You can write your own Python equivalent input method:
def input(prompt)
print(prompt) # Output prompt
$stdout.flush # Flush stdout buffers to ensure prompt appears
gets.chomp # Get user input, remove final newline with chomp
end
Now we can try it:
name = input('What is your name? ')
puts "Welcome #{name}"
For more information on the methods used here. See these:
IO.flush
String.chomp
I'm trying to receive multiple paragraphs at once from a user.
I've tried using gets, but it doesn't seem to be working... it discards the second paragraph:
#The code:
print("Paste your text here: ")
.. essay = gets
.. puts(essay)
# Getting user imput (the second sentance is a separate paragraph)
Paste your text here: I like cake.
It makes me happy.
# What the computer did for puts(essay):
I like cake.
=> nil
I expected the result to be something like this:
"I like cake.\nIt makes me happy.\n"
But it gave me "I like cake." instead.
How could I end up with my expected result?
Add paragraphs to a string until the input consists of a empty line:
str = ""
para = "init"
str << (para = gets) until para.chomp.empty? #or para == "\n"
p str
Here's an alternative, with a slightly different logic
def getps
save, $/ = $/, "\n\n"
gets.chomp
ensure
$/ = save
end
str = getps
The global variable $/ is what Ruby uses to find out what line end is. gets gets things till line end. If we tell Ruby that line end is two newlines, then gets waits till we have two newlines in a row till it exits. Since we don't need them, we'll just chomp them off. The rest of the code is just to ensure that $/ gets restored properly afterwards so normal gets is not messed up forever.
I learned that gets creates a new line and asks the user to input something, and gets.chomp does the same thing except that it does not create a new line. gets must return an object, so you can call a method on it, right? If so, lets name that object returned by gets as tmp, then you can call the chomp method of tmp. But before gets returns tmp, it should print a new line on the screen. So what does chomp do? Does it remove the new line after the gets created it?
Another way to re-expound my question is: Are the following actions performed when I call gets.chomp?
gets prints a new line
gets returns tmp
tmp.chomp removes the new line
User input
Is this the right order?
gets lets the user input a line and returns it as a value to your program. This value includes the trailing line break. If you then call chomp on that value, this line break is cut off. So no, what you have there is incorrect, it should rather be:
gets gets a line of text, including a line break at the end.
This is the user input
gets returns that line of text as a string value.
Calling chomp on that value removes the line break
The fact that you see the line of text on the screen is only because you entered it there in the first place. gets does not magically suppress output of things you entered.
The question shouldn't be "Is this the right order?" but more "is this is the right way of approaching this?"
Consider this, which is more or less what you want to achieve:
You assign a variable called tmp the return value of gets, which is a String.
Then you call String's chomp method on that object and you can see that chomp removed the trailing new-line.
Actually what chomp does, is remove the Enter character ("\n") at the end of your string. When you type h e l l o, one character at a time, and then press Enter gets takes all the letters and the Enter key's new-line character ("\n").
1. tmp = gets
hello
=>"hello\n"
2. tmp.chomp
"hello"
gets is your user's input. Also, it's good to know that *gets means "get string" and puts means "put string". That means these methods are dealing with Strings only.
chomp is the method to remove trailing new line character i.e. '\n' from the the string.
whenever "gets" is use to take i/p from user it appends new line character i.e.'\n' in the end of the string.So to remove '\n' from the string 'chomp' is used.
str = "Hello ruby\n"
str = str.chomp
puts str
o/p
"Hello ruby"
chomp returns a new String with the given record separator removed from the end of str (if present).
See the Ruby String API for more information.
"gets" allows user input but a new line will be added after the string (string means text or a sequence of characters)
"gets.chomp" allows user input as well just like "gets", but there is
not going to be a new line that is added after the string.
Proof that there are differences between them:
Gets.chomp
puts "Enter first text:"
text1 = gets.chomp
puts "Enter second text:"
text2 = gets.chomp
puts text1 + text2
Gets:
puts "Enter first text:"
text1 = gets
puts "Enter second text:"
text2 = gets
puts text1 + text2
Copy paste the code I gave you, run and you will see and know that they are both different.
For example:
x = gets
y = gets
puts x+y
and
x = gets.chomp
y = gets.chomp
puts x+y
Now run the two examples separately and see the difference.
I understand about the \n that's automatically at the end of puts and gets, and how to deal with those, but is there a way to keep the display point (the 'cursor position', if you will) from moving to a new line after hitting enter for input with gets ?
e.g.
print 'Hello, my name is '
a = gets.chomp
print ', what's your name?'
would end up looking like
Hello, my name is Jeremiah, what's your name?
You can do this by using the (very poorly documented) getch:
require 'io/console'
require 'io/wait'
loop do
chars = STDIN.getch
chars << STDIN.getch while STDIN.ready? # Process multi-char paste
break if ["\r", "\n", "\r\n"].include?(chars)
STDOUT.print chars
end
References:
http://ruby-doc.org/stdlib-2.1.0/libdoc/io/console/rdoc/IO.html#method-i-getch
http://ruby-doc.org/stdlib-2.1.0/libdoc/io/wait/rdoc/IO.html#method-i-ready-3F
Related follow-up question:
enter & IOError: byte oriented read for character buffered IO
Perhaps I'm missing something, but 'gets.chomp' works just fine does it not? To do what you want, you have to escape the apostrophe or use double-quotes, and you need to include what the user enters in the string that gets printed:
print 'Hello, my name is '
a = gets.chomp
print "#{a}, what's your name?"
# => Hello, my name is Jeremiah, what's your name?
Works for me. (Edit: Works in TextMate, not Terminal)
Otherwise, you could just do something like this, but I realise it's not quite what you were asking for:
puts "Enter name"
a = gets.chomp
puts "Hello, my name is #{a}, what's your name?"
I'm trying to write a very simple ruby script that opens a text file, removes the \n from the end of lines UNLESS the line starts with a non-alphabetic character OR the line itself is blank (\n).
The code below works fine, except that it skips all of the content beyond the last \n line. When I add \n\n to the end of the file, it works perfectly. Examples: A file with this text in it works great and pulls everything to one line:
Hello
there my
friend how are you?
becomes Hello there my friend how are you?
But text like this:
Hello
there
my friend
how
are you today
returns just Hello and There, and completely skips the last 3 lines. If I add 2 blank lines to the end, it will pick up everything and behave as I want it to.
Can anybody explain to me why this happens? Obviously I know I can fix this instance by appending \n\n to the end of the source file at the start, but that doesn't help me understand why the .gets isn't working as I'd expect.
Thanks in advance for any help!
source_file_name = "somefile.txt"
destination_file_name = "some_other_file.txt"
source_file = File.new(source_file_name, "r")
para = []
x = ""
while (line = source_file.gets)
if line != "\n"
if line[0].match(/[A-z]/) #If the first character is a letter
x += line.chomp + " "
else
x += "\n" + line.chomp + " "
end
else
para[para.length] = x
x = ""
end
end
source_file.close
fixed_file = File.open(destination_file_name, "w")
para.each do |paragraph|
fixed_file << "#{paragraph}\n\n"
end
fixed_file.close
Your problem lies in the fact you only add your string x to the para array if and only if you encounter an empty line ('\n'). Since your second example does not contain the empty line at the end, the final contents of x are never added to the para array.
The easy way to fix this without changing any of your code, is add the following lines after closing your while loop:
if(x != "")
para.push(x)
end
I would prefer to add the strings to my array right away rather then appending them onto x until you hit an empty line, but this should work with your solution.
Also,
para.push(x)
para << x
both read much nicer and look more straightforward than
para[para.length] = x
That one threw me off for a second, since in non-dynamic languages, that would give you an error. I advise using one of those instead, simply because it's more readable.
Your code is like a c code to me, ruby way should be this, which substitutes your above 100 lines.
File.write "dest.txt", File.read("src.txt")
It's easier to use a multiline regex. Maybe:
source_file.read.gsub(/(?<!\n)\n([a-z])/im, ' \\1')