Making things is only available inside Ruby blocks

Is there a way to make methods and functions only available inside blocks? What I am trying to do:

some_block do
    available_only_in_block
    is_this_here?
    okay_cool
end

      

But is_this_here?

, okay_cool

etc. are only available inside this block, not outside it. Any ideas?

+2


source to share


1 answer


Pass the object using the methods you want to use as an argument in the block. This is a pattern that is widely used in Ruby, for example, IO.open

or an XML constructor .

some_block do |thing|
    thing.available_only_in_block
    thing.is_this_here?
    thing.okay_cool
end

      

Note that you may be close to what you asked to use instance_eval

or instance_exec

, but this is generally a bad idea as it can have some pretty unexpected consequences.



class Foo
  def bar
    "Hello"
  end
end

def with_foo &block
  Foo.new.instance_exec &block
end

with_foo { bar }      #=> "Hello"
bar = 10
with_foo { bar }      #=> 10
with_foo { self.bar } #=> "Hello

      

If you pass an argument, you always know what you will be referring to:

def with_foo
  yield Foo.new
end

with_foo { |x| x.bar }      #=> "Hello"
bar = 10
x = 20
with_foo { |x| x.bar }      #=> "Hello"

      

+6


source







All Articles