Problem with Ruby string concatenation

后端 未结 3 2058
Happy的楠姐
Happy的楠姐 2021-01-05 09:11

This works

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

But this doesn\'t

irb(main):001:0> fn         


        
相关标签:
3条回答
  • 2021-01-05 09:54

    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 讨论(0)
  • 2021-01-05 09:56

    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.

    0 讨论(0)
  • 2021-01-05 10:07

    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
    
    0 讨论(0)
提交回复
热议问题