7

This works

irb(main):001:0> name = "Rohit " "Sharma"
=> "Rohit Sharma"

But this doesn't

irb(main):001:0> fname = "Rohit "
=> "Rohit "
irb(main):002:0> lname = "Sharma"
=> "Sharma"
irb(main):003:0> name = fname lname

It gives this error

NoMethodError: undefined method `fname' for main:Object
from (irb):3

Please provide some suggestions. Thanks in advance.

UPDATE

After getting the answers I have written a blog post. Please check it out.

3 Answers 3

4

The error is related to the fact that fname would have to be a function for this to work. Instead, try

name = fname + lname

or even

name = "#{fname}#{lname}"

but where you had

name = "Rohit " "Sharma"

it is a special case, since Ruby will join the two strings automatically.

Sign up to request clarification or add additional context in comments.

4 Comments

Or name = fname << lname if you know the quirks.
Yes, that's the quirk. It's faster though.
why doesn't this work lname=" Sharma" name="Rohit" lname and gives SyntaxError. Please explain.
@Rohit: by default, you must use a +. The only situation where you can avoid it is with two double quoted strings next to each other. In the case you mention, you therefore need name = "Rohit" + lname. Hope this clears it up for you. In fact, always use + and you will be fine - there's no need to skip the +, even in the case name = "Rohit " + "Sharma".
2

When you do

name = "Rohit " "Sharma"

You don't create two Strings objects that then merge together to create one string. Instead, the Ruby (interpreter/compiler/whatever) looks at the code, and merges it together before producing a single String object.

So you can do

name = "Rohit " "Sharma"

but not

first_name_plus_space = "Rohit "
last_name = "Sharma"
name = first_name_plus_space last_name

Comments

0

Just put a + inbetween them like

name = fname + lname

string + string is defined to return a new string containing the two inputs concatenated together.

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.