3
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.

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer - it works better for large multiline statements and facilitates debugging. Nice one!
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.

2 Comments

Really? Would appreciate if you could point to some documentation? I thought that interchanging quotes didn't really matter ?
@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?
4

I use this:

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

Comments

3

Do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.