Problem with If Statement in Ruby Program - ruby

I'm super beginner to ruby, but for some reason my if statement isn't working. Whenever the name 'Cristina' is entered, the program continues to print "Hello there".
def Cus_free_makers_eg1heChallenge(str)
str = gets
if str == "Cristina"
print "Hello Cristina!"
else
print "Hello there!"
end
return str
end

Add strip to remove newline:
str = gets.strip
if str == "Cristina"
print "Hello Cristina!"
else
print "Hello there!"
end

This works:
str = gets.chomp
if str == "Cristina"
print "Hello Christina!"
else
print "Hello there!"
end
str
Ruby gets statement is usually ended with chomp or chomp! to -- you guessed it -- "chomp" aka remove the trailing newline and carriage characters. More info in Ruby doc: https://docs.ruby-lang.org/en/3.0.0/String.html#method-i-chomp
I also took the opportunity to remove return and also the trailing end as both aren't necessary.

Related

Reverse a string while keeping it in a single line

I'm trying to reverse a string using the code:
puts("Hi now it's going to be done!")
string = gets.chomp.to_s
i = string.length
while i >= 0
puts(string[i])
i = i - 1
end
It prints the string in backward order, but each word is on a single line. How can I keep all of them on a single line?
puts adds a newline to the end of the output if one isn't already present.
print does not. So do this:
while i >=0
print string[i]
i=i-1
end
puts
The final puts is because you want any further printing to be on a new line.
Try this:
"Hi now it's going to be done!".chars.inject([]) { |s, c| s.unshift(c) }.join
Or This is a little easier to follow:
string = 'Hi now it's going to be done!'
string.reverse!

ruby each_line comparison only returns last string

Code:
class Comparer
words = "asdf-asdf-e-e-a-dsf-bvc-onetwothreefourfive-bob-john"
foundWords = []
File.foreach('words.txt') do |line|
substr = "#{line}"
if words.include? substr
puts "Found " + substr
foundWords << substr
end
end
wordList = foundWords.join("\n").to_s
puts "Words found: " + wordList
end
words.txt:
one
blah-blah-blah
123-5342-123123
onetwo
onetwothree
onetwothreefour
I'd like the code to return all instances of include?, however when the code is run, wordList only contains the last line of words.txt ("onetwothreefour".) Why don't the other lines in words.txt get factored?
Because all other lines you expect to be found, they have "hidden" newline character at the end. You can see for yourself.
File.foreach('words.txt') do |line|
puts line.inspect
# or
p line
end
You can get rid of newlines by using chomp! method on line.
File.foreach('words.txt') do |line|
line.chomp!
# proceed with your logic
end

How do I write a palindrome check?

I'm currently going through some programs to learn Ruby. I've been playing around with a palindrome program for a bit, though no matter the input (a palindrome) I end up on else.
Here is some of the code I've been trying:
print "enter a string:\n"
string = gets
if string.reverse == string
print "it's a palindrome"
else
print "not a palindrome.\n"
end
Any help/advice is greatly appreciated.
The newline character is not being deleted from the string. Try this code:
print "enter a string:\n"
string = gets.chomp
if string.reverse == string
print "it's a palindrome"
else
print "not a palindrome.\n"
end
Here is some more explanation:
>> string = gets
racecar # input string
=> "racecar\n"
>> "racecar\n" == "racecar\n".reverse # "racecar\n" is not a palindrome with newline character
=> false
>> string = gets.chomp # chomp method deletes newline character
racecar
=> "racecar"
>> "racecar" == "racecar".reverse # "racecar" without a newline character is a palindrome
=> true
Learn how Ruby's puts works: It's like print, only smarter.
If a string ends with "\n", it prints it as is. If it doesn't end with "\n", it prints the line and adds "\n". Either way, you're guaranteed to have new-line added.
Knowing that, consider this:
puts "enter a string:"
string = gets
if string.reverse == string
puts "it's a palindrome"
else
puts "not a palindrome."
end
As a result, no new-lines need to be added to the strings. puts is the standard method for outputting lines to files and the console in Ruby.
The following statement will return true if it's a palindrome and false otherwise:
string == string.reverse

Ruby method to reverse characters not recursing for words

The 'reverse by characters' works but the third test "by words" doesn't -
expected: "sti gniniar"
got: "sti" (using ==)
def reverse_itti(msg, style='by_character')
new_string = ''
word = ''
if style == 'by_character'
msg.each_char do |one_char|
new_string = one_char + new_string
end
elsif style == 'by_word'
msg.each_char do |one_char|
if one_char != ' '
word+= one_char
else
new_string+= reverse_itti(word, 'by_character')
word=''
end
end
else
msg
end
new_string
end
describe "It should reverse sentences, letter by letter" do
it "reverses one word, e.g. 'rain' to 'niar'" do
reverse_itti('rain', 'by_character').should == 'niar'
end
it "reverses a sentence, e.g. 'its raining' to 'gniniar sti'" do
reverse_itti('its raining', 'by_character').should == 'gniniar sti'
end
it "reverses a sentence one word at a time, e.g. 'its raining' to 'sti gniniar'" do
reverse_itti('its raining', 'by_word').should == 'sti gniniar'
end
end
The problem is in this loop:
msg.each_char do |one_char|
if one_char != ' '
word+= one_char
else
new_string+= reverse_itti(word, 'by_character')
word=''
end
end
The else block reverses the current word and adds it to the output string, but it only runs when the loop encounters a space character. Since there is no space at the very end of the string, the last word is never added to the output. You can fix this by adding new_string+= reverse_itti(word, 'by_character') after the end of the loop.
Also, you probably want to add a space to the end of the output string in the else block, too.

How to insert 't->' after '\n'?

I have a string that might have some of \n before the actual text. I want to add t-> after the new line character or characters. That means that once there is something else than '\n' in the string I want to insert 't->'.
Is there any simple way than
what = "\nrufus: ready" #result is "\nt->rufus: ready"
#what = "\n\nrufus: ready" #result is "\n\nt->rufus: ready"
#what = "\n\nrufus\n: ready" #result is "\n\nt->rufus: ready\n"
what.length.times do |i|
if (what[i,1] != "\n")
what.insert(i,"t->")
break
end
end
If I understand right, you want the following;
"abc def" => "t->abc def"
"\n\nabc def" => "\n\nt->abc def"
As such, I'd try;
string.sub(/^\n*/) do |newlines|
"#{newlines}t->"
end
If you want to insert some text at the end of every line:
original = "Hello\nWorld\nYay"
changed = original.gsub /$/, ' More!'
puts changed
#=> Hello More!
#=> World More!
#=> Yay More!
It's not a good idea to change the string as you iterate over it.
Presumably this is what you're looking for?
"\n\n".gsub("\n", "t->\n") # => "t->\nt->\n"
(substitute every instance of "\n" with "t->\n")

Resources