Ruby: Merging variables in to a string

前端 未结 7 980
[愿得一人]
[愿得一人] 2020-12-02 10:23

I\'m looking for a better way to merge variables into a string, in Ruby.

For example if the string is something like:

\"The animal action<

7条回答
  •  情书的邮戳
    2020-12-02 10:38

    I would use the #{} constructor, as stated by the other answers. I also want to point out there is a real subtlety here to watch out for here:

    2.0.0p247 :001 > first_name = 'jim'
     => "jim" 
    2.0.0p247 :002 > second_name = 'bob'
     => "bob" 
    2.0.0p247 :003 > full_name = '#{first_name} #{second_name}'
     => "\#{first_name} \#{second_name}" # not what we expected, expected "jim bob"
    2.0.0p247 :004 > full_name = "#{first_name} #{second_name}"
     => "jim bob" #correct, what we expected
    

    While strings can be created with single quotes (as demonstrated by the first_name and last_name variables, the #{} constructor can only be used in strings with double quotes.

提交回复
热议问题