Ruby: Get last character from user input
So I am trying to find the last character from user input in Ruby.
I have 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 "this is the last char!". I tried
end_char = "test"[-1,1]
and works as it should (returns t). But it doesn't work when I use the user input as a string instead of just typing the string into myself. Help?
source to share
So when you say "Line input" and you type "foo", what's the last thing you do? Well, you hit the box! So you are really captivating "foo\n"
.
The call user_input[-1,1]
actually returns a return character \n
, which simply prints the return return in the output file.
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 returned character from the input.
Now when I run it:
stacko % ruby puts.rb
Enter in a string: hi Lupo90
0 is the last char!
source to share
Consider this IRB session:
-
I'll go into "foo":
irb(main):001:0> user_input = gets foo "foo\n"
I entered "foo" and to complete the input I had to press Return(or Enterdepending on OS and keyboard) which is "\ n" (or "\ r \ n") line, depending on whether your OS is * nix or Windows.
-
After looking at what I entered:
irb(main):002:0> user_input[-1] "\n"
-
Here's what is displayed. Note that the single quotes are on separate lines because "\ n" is a newline character:
irb(main):003:0> puts "'\n'" ' ' nil
(The final
nil
is the resultputs
and is not important for this example.)
So, it gets
returns everything you entered, including the trailing newline. Let it 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
used to isolate the end of the end of a line from the end of a line:
irb(main):010:0> "foo\n".chomp
"foo"
irb(main):011:0> "foo\r\n".chomp
"foo"
This is a really common Stack Overflow question . Perhaps looking for this would help?
source to share