Visible spaces with multiple gets on one line - ruby

I'm using Ruby, trying to make an interactive program. (Very new to this, I'm actually learning right now.)
Right now I have
puts 'Can I have your name please?
first = gets.chomp
puts 'Ok, so your first name is ' + first + '? How about your middle name?'
middle = gets.chomp
puts 'ok, so your middle name is ' + middle + '. And your last name?'
last = gets.chomp
puts 'ok, so your last name is ' + last + '?'
puts 'So your full name is ' + first + middle + last + '? That's a very nice name!
'
So far everything works but that last line. When the last line pops up it puts all 3 of the names together with no spaces in between. I've tried a combination of adding or deleting + or adding or deleting spaces or even ' However, nothing I do seems to work, it just stays the same. So how do I get some spaces in between my first middle and last name in that last line?
Thanks in advance for your help.... -John

Something like this
puts "So your full name is #{first} #{middle} #{last}? That's a very nice name!"
This is called string interpolation.

Use join:
[first, middle, last].join " "

Related

Codecademy Ruby course: Control Flow know-how

When coding in Ruby, I came up with an error about needing to state all words the user inputed. I tried to change my code to get it to output that, but the problem remained. Here is my code and the Ruby instructions.
Instructions
Add an if/else statement inside your .each.
if the current word equals the word to be redacted, then print "REDACTED " with that extra space.
Otherwise (else), print word + " ".
The extra space in both cases prevents the words from running together.
puts text = gets.chomp
puts redact = gets.chomp
words = text.split(" ")
words = ['hi', 'hello', 'what', 'why']
words.each do |word|
if gets = words
print "Redact "
else
print word + "Incorrect"
end
end
The problem it says I have with my code is... Oops, try again. Make sure to print each word from the user's text to the console unless that word is the word to be redacted; if it is, print REDACTED (all caps!).
I would appreciate all help, please and thank you.
Ben sorry these guys aren't being too helpful. :D It's been awhile but I hope this helps. In the first section titled "What you'll be building" Codecademy gives you the exact example (the answer) to the final problem in the section. This is always true and may help in the future. What you're looking for:
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp
words = text.split(" ")
words.each do |word|
if word != redact
print word + " "
else
print "REDACTED "
end
end
Have pass several years I know, but I wanted pass and let my solution for this excercise.
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp
words = text.split(',') # "," is necessary to identify each of the words
words.each do |x|
if x == redact # if words repeat, print REDACTED
print "REDACTED"
else # else, only write de word and space
print x + " "
end
end

Beginner on Ruby making a calculator

this is my first entry to StackOverflow and I'm a newbie coder.
So I'm making a simple addition calc and I added commas in the last 2 lines to print out integers ...
What am I missing? The error says
C:/Ruby193/rubystuff/ex1.rb:13: syntax error, unexpected ',' print
("The result of the addition is " +,result)
I thought this was the right thing to do ... i must have missed something simple.
print ("Please enter your name: ")
name = gets
puts ("Hello, " + name)
print ("Enter a number to add: ")
num1 = gets
print ("Enter a second number to add: ")
num2 = gets
result = Integer(num1) + Integer(num2)
print result
print ("The result of the addition is ",result)
print ("So the result of adding " + num1.chomp + " plus " + num2.chomp + " equals: ",result)
Ruby has string interpolation and I think most would argue that's the most idiomatic way of doing things. RubyMonk does a great job explaining it here
by changing the 'print' call to the puts method you can do:
puts "The result of the additions is #{result}"
There are two ways to pass arguments to a method:
in parentheses directly after the method name
without parentheses with whitespace after the method name
You have white space after the method, ergo you are using option #2 and are passing a single argument ("The result of the addition is ",result) to the method, but ("The result of the addition is ",result) is not legal syntax.

gets.chomp without moving to a new line

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?"

gets.chomp method excercise in learn to program book

I am doing excercise 5.6 out of "Learn to Program" for a class. I have the following:
puts 'What\'s your first name?'
first = gets.chomp
puts 'What\'s your middle name?'
middle = gets.chomp
puts 'What\'s your last name?'
last = gets.chomp
puts 'Hello, Nice to meet you first middle last'
And I have tried the following:
puts 'What is your first name?'
first = gets.chomp
puts 'What is your middle name?'
middle = gets.chomp
puts 'What is your last name?'
last = gets.chomp
puts 'Hello, Nice to meet you #{first} #{middle} #{last}'
When I get the last "puts" it won't get the first, middle and last name that I wrote in. It says, "Hello, nice to meet you first, middle, last....Instead of Joe John Smith for example. What am I doing wrong?
Thank you so much for your help! I really appreciate it!
When using interpolation, use double quotes " instead of single quotes '
Strings within single quotes ' do not replace variables with their values. Try using double quotes " like so:
puts "Hello, Nice to meet you #{first} #{middle} #{last}"
Single qoutes are nice if you want the string as you typed it, double quotes are useful when you want to replace variable names with their values.
You can also use %Q to have the same effect as you get with double quotes ":
x = 12
puts %Q(I need #{x} pens)
# >> I need 12 pens

Ruby File gets not reading content after last blank line \n

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

Resources