Is it possible to execute a proc within the context of another object?
I know that normally you'd do proc.call(foo), and then the block should define a parameter. I was wondering though whether I could get "self" to bind to foo so that it's not necessary to have a block parameter.
proc = Proc.new { self.hello }
class Foo
def hello
puts "Hello!"
end
end
foo = Foo.new
# How can proc be executed within the context of foo
# such that it outputs the string "Hello"?
proc.call
foo.instance_eval &proc
instance_eval can take a block instead of a string, and the & operator turns the proc into a block for use with the method call.
This is for ruby 1.9:
class MyCat
def initialize(start, &block)
#elsewhere = start
define_singleton_method(:run_elsewhere, block) if block_given?
end
end
MyCat.new('Hello'){ #elsewehere << ' world' }.run_elsewhere
Related
I'm currently working on an interface that allows me to wrap arbitrary method calls with a chain of procs. Without going into too much detail, I currently have an interface that accepts something like this:
class Spy
def initialize
#procs = []
end
def wrap(&block)
#procs << block
end
def execute
original_proc = Proc.new { call_original }
#procs.reduce(original_proc) do |memo, p|
Proc.new { p.call &memo }
end.call
end
def call_original
puts 'in the middle'
end
end
spy = Spy.new
spy.wrap do |&block|
puts 'hello'
block.call
end
spy.wrap do |&block|
block.call
puts 'goodbye'
end
spy.execute
What I'd like to do though is remove the |&block| and block.call from my API and use yield instead.
spy.wrap do
puts 'hello'
yield
end
This didn't work and raised a LocalJumpError: no block given (yield) error.
I've also tried creating methods by passing the proc the define_singleton_method in the reduce, but I haven't had any luck.
def execute
original_proc = Proc.new { call_original }
#procs.reduce(original_proc) do |memo, p|
define_singleton_method :hello, &p
Proc.new { singleton_method(:hello).call(&memo) }
end.call
end
Is there another approach I can use? Is there anyway to yield from a Proc or use the Proc to initialize something that can be yielded to?
Using yield in your wrap block does not make much sense unless you passed a block to the caller itself:
def foo
spy.wrap do
puts "executed in wrap from foo"
yield
end
end
If you call foo without a block it will raise the exception since yield can't find a block to execute. But if you pass a block to foo method then it will be invoked:
foo do
puts "foo block"
end
Will output
executed in wrap from foo
foo block
In conclusion I think you misunderstood how yield works and I don't think it is what you want to achieve here.
I want to return a multi-line block of code from one function to be executed by another function
for example
def foo
return #block
end
def bar(&block)
block.call
end
bar(foo)
Does any one know how to do this?
Ruby 1.9.3
You need to create a Proc. There are several methods that create them — primarily proc, lambda and ->. You just pass a block to one of these functions and it will wrap the block in a Proc object. (There are subtle differences in how the three methods handle arguments, but you usually don't need to care.) So you could write:
def foo
proc { puts "Look ma, I got called!" }
# you don't need the return keyword in Ruby -- the last expression reached returns automatically
end
def bar(&block)
block.call
end
bar(&foo) # You need the & operator to convert the Proc back into a block
You can return a Proc object:
def foo
return Proc.new { ... }
end
def bar(block)
block.call
end
bar(foo)
Here's the live example.
def foo
Proc.new {
# code here
}
end
No need to use return, it is implicit.
instance_eval method change self in its block, eg:
class D; end
d = D.new
d.instance_eval do
puts self # print something like #<D:0x8a6d9f4>, not 'main'!
end
If we define a method ourself(or any other methods(other than instance_eval) which takes a block), when print self, we will get 'main', which is different from instance_eval method.eg:
[1].each do |e|
puts self # print 'main'
end
How can i define a method(which takes a block) like instance_eval?
Thanks in advance.
You can write a method that accepts a proc argument, and then pass that as a proc argument to instance_eval.
class Foo
def bar(&b)
# Do something here first.
instance_eval &b
# Do something else here afterward, call it again, etc.
end
end
Foo.new.bar { puts self }
Yields
#<Foo:0x100329f00>
It's obvious:
class Object
def your_method(*args, &block)
instance_eval &block
end
end
receiver = Object.new
receiver.your_method do
puts self #=> it will print the self of receiver
end
How do I pass the parameter name in the following case..the name is being is evaluated before being passed to class_eval
class Foo
end
Foo.class_eval %Q{
def hello(name)
p "hello #{name}"
end
}
Sorry about not giving the entire scenario...
I just wanted to add a instance method dynamically to a class and that method should be able to take arguments...
the above code would not compile complaining that the name is not defined as local variable when executing in irb..
Thanks
The other answers are the "right" answer, but you could also just skip interpolating inside the p call:
Foo.class_eval %Q{
def hello(name)
p "hello \#{name}"
end
}
I thought you wanted to change the actual parameter name (possibly useful for completion or when using Pry on dynamic methods), here assuming it's in a global, but could also be passed into a method doing the class_eval:
Foo.class_eval %Q{
def hello(#{$argname})
p "hello \#{$argname}"
end
}
Really simple:
Foo.class_eval do
def hello(name)
p "hello #{name}"
end
end
Try passing a block to class_eval instead of an array (from this link):
class Foo
end
Foo.class_eval {
def hello(name)
p "hello #{name}"
end
}
You then can call the instance method hello in the usual fashion:
boo = Foo.new
boo.hello("you")
which produces:
>> boo.hello("you")
"hello you"
=> nil
class Foo
end
Foo.class_eval do
define_method :hello do |name|
p "hello #{name}"
end
end
Foo.new.hello("coool") # => "hello coool"
If a block is a closure, why does this code does not work, and how to make it work?
def R(arg)
Class.new do
def foo
puts arg
end
end
end
class A < R("Hello!")
end
A.new.foo #throws undefined local variable or method `arg' for #<A:0x2840538>
Blocks are closures and arg is indeed available inside the Class.new block. It's just not available inside the foo method because def starts a new scope. If you replace def with define_method, which takes a block, you'll see the result you want:
def R(arg)
Class.new do
define_method(:foo) do
puts arg
end
end
end
class A < R("Hello!")
end
A.new.foo # Prints: Hello!
If you define the class dynamically, you can alter it as you like:
def R(arg)
c = Class.new
# Send the block through as a closure, not as an inline method
# definition which interprets variables always as local to the block.
c.send(:define_method, :foo) do
arg
end
c
end
class A < R("Hello!")
end
puts A.new.foo.inspect
# => "Hello!"