Ruby: Why is this printed on a new line? - ruby

I have:
print 'Please enter the total amount of your bill: '
bill_amount = gets.chomp.to_f
print 'What percentage tip do you want? '
tip = gets.chomp.to_f / 100
puts "Your bill amount will be #{bill_amount * tip}"
When the final "puts" is printed, it's printed on a new line. Why is this? The previous "print something" statement was "print" which doesn't insert a new line. Even if I put "print" instead of "puts" for the end line, it still prints in a new line. What's going on? How can I make it so the end statement prints in the same line as "What percentage tip do you want"?

It is printed on the next line because you press ENTER to finish inputing your data (and therefore you make a new line). Didn't it confuse you that second print also goes to a new line?

Its printing in next line as after the user enters the value for 'Tip' , he/she has to press the 'enter' key to proceed.
The value of variable 'tip' will be free of any trailing white spaces (beacuse of .chomp).
However on the screen, the enter key has already moved the user to the next line and hence the statement prints in the next line.

Related

Ruby Throw-Catch tutorial unclear

def promptAndGet(prompt)
print prompt
res = readline.chomp
throw :quitRequested if res == "!"
return res
end
catch :quitRequested do
name = promptAndGet("Name: ")
age = promptAndGet("Age: ")
sex = promptAndGet("Sex: ")
# ..
# process information
end
promptAndGet("Name:")
From https://www.tutorialspoint.com/ruby/ruby_exceptions.htm
When executed normally, it goes through name, age, sex, and back to name again, despite the prompt only asking for the name.
Why does this happen instead of "Name" just being asked?
That final line promptAndGet("Name") does not get immediately executed, since it's after the catch block.
The normal flow is that everything within the catch :quitRequested block gets executed immediately, in order. That's why you get all 3 prompts inside. If you answer all 3 prompts, you'll also get to the prompt on the last line.
If you answer ! to any of the three prompts, the block will terminate. So you will not get the remaining prompts inside the block.
You'll still get the prompt on the last line since it's outside of the catch.
throw is what terminates the catch block - not what initiates it.
Also, if you answer ! to that final prompt outside of the catch block, you'll get an error, because the throw was uncaught.

How to read the second line in a document.txt and then make a loop that reads line +1 in this document

My bot reads emails one by one from a document.txt file and after login with this email the bot outputs the comments that I have in another file.
I have reached the point that the bot reads the emails but I want that a specific account makes a specific and not a repeated comment.
So I have in mind the solution of reading a specific line from the comments file.
For example account 1 reads and puts line 1 of the comments file. I want to know how can I read the second line from a comments file.
This is the code part when I read comments one by one but I want to read for example line two or three!
file = 'comments.txt'
File.readlines(file).each do |line|
comment = ["#{line}"]
comment.each { |val|
comment = ["#{val}"]
}
end
File.readlines returns array. So you can do everything you want
lines = []
File.readlines(path_to_file, chomp: true).each.with_index(1) do |line, line_number|
lines << (line_number == 2 ? 'Special line' : line)
end
Try the below.
# set the line number to read
line_number = 2 # <== Reading 2nd line
comment = IO.readlines('comments.txt')[line_number-1]
Your code is overwriting the comment variable in each iteration.
I'd write your code like this:
lines = File.readlines('comments.txt')
lines.each do |line|
# entire line
end
In the loop you can do a lot of things with the single line, unfortunately I don't get 100% what you want to do (one comment vs. multiple, always the same for specific users, etc.) I hope this helps anyway.

Check 4 chars with regex Ruby console input

I have 4 chars, first one is letter 'L' for example, the other two are numbers and the last one is letter again, all of them are separated by one space. User is entering them in the Ruby console. I need to check that they are separated by one space and don't have other weird characters and that there is nothing after the last letter.
So if a user enters for example gets.chomp = 'L 5 7 A', I need to check that everything is ok and separated by only one space and return input[1], input[2], input[3]. How can I do that? Thanks.
You can do something like this:
puts "Enter string"
input = gets.chomp
r = /^(L)\s(\d)\s(\d)\s([A-Z])$/
matches = input.match r
puts matches ? "inputs: #{$1}, #{$2}, #{$3}, #{$4}" : "input-format incorrect"
Here $1 is the first capture, similarly for $2, $3 etc. If you want to store the result in an array you can use:
matches = input.match(r).to_a
then the first element is the entire match, followed by each capture.
Try
/^\w\s(\d)\s(\d)\s(\w)$/
Rubular is a good sandbox site for experimenting with and debugging regexes.

Finding and saving the last occurrence of a string using awk

I need to find the last occurrence of a string in a plain text file (no delimiters or columns) and save its line number and the entire line in variables for later use in my script
Then I need to check if there is an occurrence of a second string after the line we just found.
I'm unsure of how to do this, I'm a scrub at bash. I'm not sure how to save results of awk in a variable, and I'm not sure of the logic i'd need to find the last occurrence of a string. Any advice/guidance would be amazing
# Remember last line on which we saw "string_to_match", and the line itself
/string_to_match/ { last1 = NR; line=$0 }
# Remember last line on which we saw "second_string"
/second_string/ { last2 = NR }
# At the end of the file, if last2 was after last1, print it.
END { if (last2 > last1) print last2 }
Basically just process each line in turn and every time you find the first string update the last1 and line variables.
Similarly, every time you see the first string update the last2 variable.
When you reach the end of the file last1 will be the last line on which you saw the first string. At that point you can see if the second string was seen after that point. You can also do whatever processing you need using last1 and line.

Ruby: String Comparison Issues

I'm currently learning Ruby, and am enjoying most everything except a small string comparason issue.
answer = gets()
if (answer == "M")
print("Please enter how many numbers you'd like to multiply: ")
elsif (answer. == "A")
print("Please enter how many numbers you'd like to sum: ")
else
print("Invalid answer.")
print("\n")
return 0
end
What I'm doing is I'm using gets() to test whether the user wants to multiply their input or add it (I've tested both functions; they work), which I later get with some more input functions and float translations (which also work).
What happens is that I enter A and I get "Invalid answer."The same happens with M.
What is happening here? (I've also used .eql? (sp), that returns bubcus as well)
gets returns the entire string entered, including the newline, so when they type "M" and press enter the string you get back is "M\n". To get rid of the trailing newline, use String#chomp, i.e replace your first line with answer = gets.chomp.
The issue is that Ruby is including the carriage return in the value.
Change your first line to:
answer = gets().strip
And your script will run as expected.
Also, you should use puts instead of two print statements as puts auto adds the newline character.
your answer is getting returned with a carriage return appended. So input "A" is never equal to "A", but "A(return)"
You can see this if you change your reject line to print("Invalid answer.[#{answer}]"). You could also change your comparison to if (answer.chomp == ..)
I've never used gets put I think if you hit enter your variable answer will probably contain the '\n' try calling .chomp to remove it.
Add a newline when you check your answer...
answer == "M\n"
answer == "A\n"
Or chomp your string first: answer = gets.chomp

Resources