mlzboy
mlzboy

Reputation: 14691

How do I eval multiple lines of code in ruby?

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.

Upvotes: 3

Views: 3035

Answers (4)

balu
balu

Reputation: 3689

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

Upvotes: 8

horseyguy
horseyguy

Reputation: 29895

I use this:

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

Upvotes: 4

Andrew Grimm
Andrew Grimm

Reputation: 81470

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.

Upvotes: 5

Zabba
Zabba

Reputation: 65467

Do:

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

Upvotes: 3

Related Questions