How do I write a palindrome check? - ruby

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

Related

Problem with If Statement in Ruby Program

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.

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 detects variable is string, but ends the script without breaking loop [duplicate]

I need to check whether my variable is an Integer or a String.
The code below will just break the loop, without warning me for an illegal character. Can anyone help me to find the mistake?
x = 0
while x == 0
name = gets.chomp.capitalize
if name.empty?
puts "No input. Try again"
elsif name.is_a? Integer
puts "Illegal character: Integer "
else
x = 1
end
end
Because gets returns a string you need to find out if the string represents a number (and only a number).
First, translate your string to an integer with to_i. Please note that to_i returns 0 for strings that do not include numbers. In a second step check if translating this integer back into a string matches the original string
string.to_i.to_s == string
Note that this is just a simple example, it wouldn't work for example with the string 00.
Another way might be checking if the string only contains numbers. That could be done by using a regexp:
string.match(/\A\d+\z/)
You can do something like this:
loop do
puts "Enter name"
name = gets.chomp
if name.empty?
puts "No input, try again"
elsif name.scan(/\d+/).any?
puts "Illegal character: Integer"
else
raise StopIteration
end
end
case-expression
Or use a case-expression to tidy things up.
loop do
puts "Enter name"
case gets.chomp
when ''
puts "No input, try again"
when /\d/
puts "Illegal character: Integer"
else
raise StopIteration
end
end
See String#scan, Array#any? and StopIteration for further details

Check whether my variable is an Integer or String

I need to check whether my variable is an Integer or a String.
The code below will just break the loop, without warning me for an illegal character. Can anyone help me to find the mistake?
x = 0
while x == 0
name = gets.chomp.capitalize
if name.empty?
puts "No input. Try again"
elsif name.is_a? Integer
puts "Illegal character: Integer "
else
x = 1
end
end
Because gets returns a string you need to find out if the string represents a number (and only a number).
First, translate your string to an integer with to_i. Please note that to_i returns 0 for strings that do not include numbers. In a second step check if translating this integer back into a string matches the original string
string.to_i.to_s == string
Note that this is just a simple example, it wouldn't work for example with the string 00.
Another way might be checking if the string only contains numbers. That could be done by using a regexp:
string.match(/\A\d+\z/)
You can do something like this:
loop do
puts "Enter name"
name = gets.chomp
if name.empty?
puts "No input, try again"
elsif name.scan(/\d+/).any?
puts "Illegal character: Integer"
else
raise StopIteration
end
end
case-expression
Or use a case-expression to tidy things up.
loop do
puts "Enter name"
case gets.chomp
when ''
puts "No input, try again"
when /\d/
puts "Illegal character: Integer"
else
raise StopIteration
end
end
See String#scan, Array#any? and StopIteration for further details

Ruby: Get last character from user input

So I'm trying to find the last character from user input in Ruby.
I've tried the following-
print "Enter in a string: "
user_input = gets
end_char = user_input[-1,1]
puts "#{end_char} is the last char!"
But it returns
" is the last char!".
I've tried
end_char = "test"[-1,1]
and that works as it should (returns t). But its not working when I use user input as the string instead of just typing in a string itself. Help?
So when you say "Enter in a string" and you type "foo", what's the last thing you do? Well you hit enter obviously! So what you actually capture is "foo\n".
Calling user_input[-1,1] actually gives back the \n return symbol which just prints a break return in the output.
print "Enter in a string: "
user_input = gets.chomp
end_char = user_input[-1,1]
puts "#{end_char} is the last char!"
the #chomp method actually removes the return character from the input.
Now when I run it:
stacko % ruby puts.rb
Enter in a string: hi Lupo90
0 is the last char!
Consider this IRB session:
I'll enter "foo":
irb(main):001:0> user_input = gets
foo
"foo\n"
I entered "foo", and to terminate the input I had to press Return (or Enter depending on the OS and keyboard), which is the "\n" (or "\r\n") line-ending, depending on whether your OS is *nix or Windows.
Looking at what I entered:
irb(main):002:0> user_input[-1]
"\n"
Here's what is output. Notice that the single-quotes are on separate lines because a "\n" is a new-line character:
irb(main):003:0> puts "'\n'"
'
'
nil
(The trailing nil is the result of puts and isn't important for this example.)
So, gets returned everything entered, including the trailing new-line. Let's fix that:
irb(main):004:0> user_input = gets.chomp
foo
"foo"
irb(main):005:0> user_input[-1]
"o"
irb(main):006:0> puts '"%s" is the last char' % [user_input[-1]]
"o" is the last char
chomp is used to strip trailing line-end from the end of a string:
irb(main):010:0> "foo\n".chomp
"foo"
irb(main):011:0> "foo\r\n".chomp
"foo"
This is a really common question on Stack Overflow. Perhaps searching for it would have helped?

Resources