The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Cheaper alternative to Binding.of_caller

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eigen Class

Posts: 358
Nickname: eigenclass
Registered: Oct, 2005

Eigenclass is a hardcore Ruby blog.
Cheaper alternative to Binding.of_caller Posted: Jul 20, 2006 6:05 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Eigen Class.
Original Post: Cheaper alternative to Binding.of_caller
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eigen Class
Latest Posts From Eigenclass

Advertisement

Here's a trick to modify local variables in the caller scope without using Binding.of_caller. It's not as general, but much faster when it applies (when you're using a "literal" block):

def foo(a, &block)
  raise "Want a block" unless block_given?
  eval("lambda{|x| whatever = x}", block).call(1)
  yield a + 1
end

whatever = nil
a = foo(1){|x| 2 * x }
whatever                          # => 1
a                                 # => 4

Why use

  eval("lambda{|x| whatever = x}", block).call(1)

instead of simply

  eval("whatever = 1", block)

? The example is admittedly stupid, since in a less simplistic (but rare!) situation you'd have something more like


Read more...

Read: Cheaper alternative to Binding.of_caller

Topic: Lots of JRuby Love Today Previous Topic   Next Topic Topic: Tag Cloud Howto Using Ruby on Rails

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use