Can you eval code in the context of a caller in Ruby?

后端 未结 5 534
说谎
说谎 2020-12-06 09:46

Essentially I\'m wondering if the following can be done in Ruby.

So for example:

def bar(symbol) 
  # magic code goes here, it outputs \"a = 100\"          


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-06 09:56

    Here's a easier syntax hack, using a passed in block binding:

      def loginfo &block
        what = yield.to_s
        evaled = eval(what, block.binding)
        Rails.logger.info "#{what} = #{evaled.inspect}"
      end
    

    called like this:

      x = 1
      loginfo{ :x }
    

    will log out:

      x = 1
    

提交回复
热议问题