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
  • 74,534
  • 52
  • 194
  • 322
mlzboy
  • 13,836
  • 23
  • 73
  • 97

4 Answers4

7

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,529
  • 1
  • 23
  • 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
  • 74,534
  • 52
  • 194
  • 322
  • 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
3

I use this:

eval %{
  puts 'ff'
  puts 'hello'
}
horseyguy
  • 28,690
  • 18
  • 100
  • 139
2

Do:

eval('puts "ff";puts "ff"')
Zabba
  • 62,418
  • 46
  • 175
  • 205