Ruby: eval with string interpolation

后端 未结 2 525
独厮守ぢ
独厮守ぢ 2021-02-04 12:09

I don\'t understand, why eval works like this:

\"123 #{456.to_s} 789\" # => \"123 456 789\"
eval(\'123 #{456.to_s} 789\') # => 123
         


        
2条回答
  •  误落风尘
    2021-02-04 12:42

    You wanted:

    eval('"123 #{456.to_s} 789"')
    

    . . . hopefully you can see why?

    The code passed to the interpretter from eval is exactly as if you had written it (into irb, or as part of a .rb file), so if you want an eval to output a string value, the string you evaluate must include the quotes that make the expression inside it a String.

提交回复
热议问题