Search code examples
rubyblockinline

Ruby block's result as an argument


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?


Solution

  • 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 to obj’s instance variables. In the version of instance_eval that takes a String, 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