2
eval('puts "ff"\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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
mlzboy
  • 14,343
  • 23
  • 76
  • 97

4 Answers4

8

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
balu
  • 3,619
  • 1
  • 25
  • 18
  • This should be the accepted answer - it works better for large multiline statements and facilitates debugging. Nice one! – Steven Garcia Jan 07 '13 at 19:49
5
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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • Really? Would appreciate if you could point to some documentation? I thought that interchanging quotes didn't really matter ? – Zabba Nov 03 '10 at 06:34
  • @Zabba: You can try it in irb, or you can look at documentation mentioned at [Backslashes in Single quoted strings vs. Double quoted strings in Ruby?](http://stackoverflow.com/questions/648156/backslashes-in-single-quoted-strings-vs-double-quoted-strings-in-ruby) – Andrew Grimm Nov 03 '10 at 06:48
4

I use this:

eval %{
  puts 'ff'
  puts 'hello'
}
horseyguy
  • 29,455
  • 20
  • 103
  • 145
2

Do:

eval('puts "ff";puts "ff"')
Zabba
  • 64,285
  • 47
  • 179
  • 207