开发者

How do I eval multiple lines of code in ruby?

开发者 https://www.devze.com 2023-01-23 10:24 出处:网络
eval(\'puts \"f开发者_开发技巧f\"\\nputs \"ff\"\') I tried to use two expressions in one eval but it doesn\'t execute?
eval('puts "f开发者_开发技巧f"\nputs "ff"')

I tried to use two expressions in one eval but it doesn't execute?

How do I do this? I want to know because I want to dynamically execute partial code.


With heredoc syntax. File and line number are passed to give reference information in back traces.

eval(<<-CODE, __FILE__, __LINE__ +1 )
  some(:ruby);
  code
  # and comments
CODE


eval("puts 'ff'\nputs 'ff'")

also works. '\n' gets treated as literally a slash and an n, because single quotes work differently to double quotes.


I use this:

eval %{
  puts 'ff'
  puts 'hello'
}


Do:

eval('puts "ff";puts "ff"')
0

精彩评论

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

关注公众号