开发者

Problem with Ruby string concatenation

Thi开发者_如何学Cs 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.


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.


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


Just put a + inbetween them like

name = fname + lname

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜