How can I store my `gets` method in a variable? - ruby

I need to store a user input in a variable. This is my code:
puts "Hi! I'm HAL, what's your name?"
gets.strip
name = gets.strip
greeting(name)
This isn't working.

This may not be what you want, but it answers the question posed in the title.
You can hold the method Kernel#gets in a variable like so:
m = method(:gets)
#=> #<Method: Object(Kernel)#gets>
Now let's use it.
def greeting(name)
puts "Me? I'm #{name}"
end
puts "Hi! I'm HAL, what's your name?"
name = m.call.strip # "Dave Bowman" is entered
name holds the user's response, after the string is stripped of any enclosing whitespace and the trailing newline character.
greeting(name)
Me? I'm Dave Bowman

Try this:
puts "Hi! I'm HAL, what's your name?"
name = gets.strip
greeting(name)

Related

Using regex in simple if statements?

Instead of doing:
puts "what type of input?"
input = gets.chomp
if %W[Int INT i I Ints ints].include?(input)
puts "enter int"
i = gets.to_i
I want to use regex to interpret string user input. For example,
puts "are you entering in a string, an int or a float?"
case gets
when /\A(string|s)\z/i
puts "enter in a string"
gets.chomp
when /\A(int|i)\z/i
puts "enter an int"
gets.to_i
when /\A(float|f)\z/i
puts "enter a float"
gets.to_f
end
What is the syntax in order to get the same result but using if statements instead of case statement?
gets returns a string with a trailing carriage return. What you need is to match the ending against \Z, not \z.
puts "are you entering in a string, an int or a float?"
case gets
when /\As(tring)?\Z/i
puts "enter in a string"
gets.chomp
when /\Ai(nt)?\Z/i
puts "enter an int"
gets.to_i
when /\Af(loat)?\z/i
puts "enter a float"
gets.to_f
else puts "Didn’t work"
end
I also slightly updated regexps to clearly show the intent.
If you want to turn your case into an if, you have to store the expression intended for the gets into a variable:
response=gets.chomp
if /..../ =~ response
...
elsif /.../ =~ response
....
....
else
...
end

What does gets.chomp do?

I was also wondering if I always have to put the exclamation point after .capitalize!
print "What's your first name? "
first_name = gets.chomp
first_name.capitalize!
print "What's your last name? "
last_name = gets.chomp
last_name.capitalize!
print "What city are you from? "
city = gets.chomp
city.capitalize!
print "What state or province are you from? "
state = gets.chomp
state.capitalize!.upcase!
puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"
What does gets.chomp do?
If you type denisreturn then gets would return "denis\n" where \n is the line feed character from the return key. chomp removes such trailing newline:
"denis\n".chomp
#=> "denis"
I was also wondering if I always have to put the exclamation point after .capitalize!
In general, a bang method is a method like any other: (from the documentation for method names)
The bang methods (! at the end of method name) are called and executed just like any other method.
But:
[...] by convention, a method with an exclamation point or bang is considered dangerous.
Dangerous can mean various things, depending on the context. For built-in methods from Ruby's core library it usually means:
[...] that when a method ends with a bang (!), it indicates that unlike its non-bang equivalent, permanently modifies its receiver.
So capitalize! (with !) will modify first_name: (the method's receiver)
first_name = 'denis' #=> "denis"
first_name.capitalize! #=> "Denis"
first_name #=> "Denis"
capitalize! will also return nil if the string is already capitalized:
first_name = 'Denis' #=> "Denis"
first_name.capitalize! #=> nil
first_name #=> "Denis"
Whereas capitalize (without !) will always return a new (capitalized) string, leaving first_name unchanged:
first_name = 'denis' #=> "denis"
first_name.capitalize #=> "Denis"
first_name #=> "denis"
Apparently, the capitalize call above doesn't make much sense because the return value is not used anywhere. You usually want to do something with that new string like assigning it to a variable:
capitalized_first_name = first_name.capitalize
or passing it to a method:
puts "Your name is #{first_name.capitalize}"
chomp removes the linebreak character at the end of the string input.
Adding the ! will mutate the value of your variable. It is not required. It depends on your use case.
foo = 'foo'
foo.capitalize
print foo
=> 'foo'
bar = 'bar'
bar.capitalize!
print bar
=> 'Bar'
Of course you don't need the "!". Let's try to get by without them:
print "What's your first name? "
first_name = gets.chomp.capitalize
print "What's your last name? "
last_name = gets.chomp.capitalize
print "What city are you from? "
city = gets.chomp.capitalize
print "What state or province are you from? "
state = gets.chomp.upcase
puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"
There you go. You can avoid mutation and just manipulate your strings with standard methods. No "!" methods need apply!
ps: capitalize followed by upcase is the same as just upcase.

How to display modified string?

I am creating a Daffy Duck speech converter (Very simple. Straight from CodeCademy) and I am having an issue with displaying the modified entry from the user.
Code:
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print #{user_input}
else puts "I couldn't find any 's' in your entry. Please try again."
end
It will change any 's' in your entry to a 'th', therefore, making it sound like a Daffy Duck once read aloud. When I enter it into the interpreter, it will not display the modified string. It will just display the original entry by the user.
EDIT:
Thanks to the users below, the code is fixed, and I added a notice to the user with converted text. Thanks guys!
A # outside a string starts a comment, so #{user_input} is ignored, i.e.
print #{user_input}
is equivalent to
print
You might wonder why a single print outputs the original input. This is because without arguments print will print $_. That's a global variable which is set by gets:
user_input = gets.chomp # assume we enter "foo"
user_input #=> "foo"
$_ #=> "foo\n"
Everything works as expected if you pass a string literal:
print "#{user_input}"
or simply
print user_input
Note that gsub! returns nil if no substitutions were performed, so you can actually use it in your if statement:
if user_input.gsub!(/s/, "th")
print user_input
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You just need to add double quotes around the string interpolation. Otherwise your code was just returning the input.
puts "What would you like to convert to Daffy Duck language?"
user_input = gets.chomp
user_input.downcase!
if user_input.include? "s"
user_input.gsub!(/s/, "th")
print "#{user_input}"
else
puts "I couldn't find any 's' in your entry. Please try again."
end
You don't even need interpolation, actually. print user_input works. Notice how StackOverflow was even syntax highlighting your code as a comment. :)

setting variables equal to 'gets' in Ruby

I want to write a program that asks for two strings from the user and searches for one within the other, but I'm having some trouble making it work. The following returns "not" even when the given character is present within the string. Does anyone know what I'm doing wrong?
puts 'Enter the string that you would like to search'
content = gets
puts 'What character would you like to find?'
query = gets
if content.include? query
puts "here"
else
puts "not"
end
gets returns the string from the user including the newline character '\n' at the end. If the user enters "Hello world" and "Hello", then the strings really are:
"Hello World\n"
"Hello\n"
That makes it obvious, why your code does not find a match.
Use chomp to remove that newline characters from the end of the string.
puts 'Enter the string that you would like to search'
content = gets.chomp
puts 'What character would you like to find?'
query = gets.chomp
if content.include?(query)
puts "here"
else
puts "not"
end

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

Resources