Reputation: 26680
There are many examples how to pass Ruby block as an argument, but these solutions pass the block itself.
I need a solution that takes some variable, executes an inline code block passing this variable as a parameter for the block, and the return value as an argument to the calling method. Something like:
a = 555
b = a.some_method { |value|
#Do some stuff with value
return result
}
or
a = 555
b = some_method(a) { |value|
#Do some stuff with value
return result
}
I could imagine a custom function:
class Object
def some_method(&block)
block.call(self)
end
end
or
def some_method(arg, &block)
block.call(arg)
end
but are there standard means present?
Upvotes: 0
Views: 617
Reputation: 118299
I think, you are looking for instance_eval
.
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (
obj
). In order to set the context, the variable self is set to obj while the code is executing, giving the code access toobj’s
instance variables. In the version ofinstance_eval
that takes aString
, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.
a = 55
a.instance_eval do |obj|
# some operation on the object and stored it to the
# variable and then returned it back
result = obj / 5 # last stament, and value of this expression will be
# returned which is 11
end # => 11
Upvotes: 1
Reputation: 766
This is exactly how @Arup Rakshit commented. Use tap
def compute(x)
x + 1
end
compute(3).tap do |val|
logger.info(val)
end # => 4
Upvotes: 0