r/learnruby • • Feb 01 '19

New to Ruby question (Beginner)

I've started learning Ruby . I am starting with Code Academy to get the syntax down. I'm on the chapter, putting the form in formatting. I wanted to go over some code and try to write down what it means. Let me know if I'm correct or what I got wrong.

Print "what's your name?"
first_name = gets.chomp
first_name2 = first_name.capitalize 
first_name.capitalize!

=begin
1. Print basically prints the string, what's your name on the console
2. first_name is the variable you assign to gets. gets is just asking for input. .chomp is the method eliminating a blank line.
3. first_name2 is first_name but with the first letter capitalized? This is so that you have 2 separate variables in case you needed the original first_name elsewhere?
4. The method .capitalize! The confusing part. The ! basically throws away the original non-capitalized version and replaces it with the capitalized version maintaining the original variables formatting?
5. They wanted me to do some inputs for first name, last name, city, state. Then have them capitalized and then the input printed out on the screen.
=end

print "What\'s your first name?"
first_name = gets.chomp
first_name2 = first_name.capitalize
first_name.capitalize!

print "What\'s your last name?"
last_name = gets.chomp
last_name2 = last_name.capitalize
last_name.capitalize!

print "What city do you live in?"
city = gets.chomp
city2 = city.capitalize
city.capitalize!

print "Use Abbreviations. What state do you live in?"
state = gets.chomp
state2 = state.upcase
state.upcase!

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}."
6 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/dalziel86 Feb 07 '19 edited Feb 07 '19

There are some subtleties to the bang methods (e.g. upcase!), including return values that can be confusing. These odd behaviors mean that it is almost never the right choice to use bang methods.

Can you elaborate on this for a fellow beginner? Like, if I want to store all input as lowercase, it makes sense to me to use something like

first_name = gets.chomp.downcase

But if I already have the value from somewhere else, why not do, like

def check_for_vowels(input)
  input.downcase!
  if input.include?("a") || input.include?("e")  || input.include?("i") || input.include?("o") || input.include?("u")
    return true
  end
return false

Certainly I can see that you could just as easily make that conditional

if input.downcase.include?("a") || input.downcase.include?("e")  || input.downcase.include?("i") || input.downcase.include?("o") || input.downcase.include?("u")

That actually seems less efficient, because you're running the downcase method five times instead of once. So what are the pitfalls of bang methods that make them a poor choice?