0

Hi I am new to ruby and I am trying to create a first a last name variables from a single user input line and then concatenate their full name back to them. This is what I have but I don't know if I am doing it correctly.

  def first
    @first
  end

  def last
    @last
  end

print "Enter your first and last name: "


first = gets.chomp
last = gets.chomp


print "Hello, " + @first + @last + "!"

end
0

2 Answers 2

2

No, you're not doing it correctly. Ditch the methods. And the instance variables. Use local variables.

print "Enter your first and last name: "


first = gets.chomp
last = gets.chomp


print "Hello, " + first + last + "!"
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! I'll be sure to give you the question answered when I can! :)
@RyanGlass it's more common to use string interpolation, i.e. "Hello, #{first} #{last}!" instead of +. And you probably want puts instead of print to add a newline.
Ryan, further to @Stefan's comment, you could skip the variables and write "Hello, #{gets.chomp} #{gets.chomp}!" or "Hello, %s %s!" % [gets.chomp}, gets.chomp]. Also, String#strip would be better than String#chomp because strip removes all leading and trailing whitespace whereas chomp only removes the newline: " cat \n".chomp #=> " cat " ; " cat \n".strip #=> "cat"...
... In real life you probably would be doing some checks on the user input rather than using it blindly. For example, what if the user entered an empty string for first and, say, "Cher" for last?
0

I figured out another way of getting the two variables from a single user input thank you for all your guys' help. This was the end code.

print "Enter your first and last name: "

first, last = gets.chomp.split

print "Hello, " + first + " " + last + "!"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.