Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Ruby string concatenation

Tags:

string

ruby

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.

like image 621
Rohit Avatar asked Dec 06 '10 08:12

Rohit


1 Answers

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.

like image 132
Peter Avatar answered Nov 02 '22 18:11

Peter