1

As you may know, there's a special variable _ of last expression in REPL's like irb and pry.

But can I get the result of last expression from Ruby platform?

Because of Ruby's dynamic nature and flexible compiler/virtual machine, maybe it's possible to get it from the Ruby's guts.

So I can avoid to write construction like this:

def some_method
  result = begin
    # some code
  end
  # do something with result
  result
end

P.S. tap is not a solution for me

megas
  • 21,401
  • 12
  • 79
  • 130
  • Well, since everything in Ruby is an expression with a value, I don't think you will find the result useful. In REPLs, the value of each entered line of code is retained which is not at all the same thing. – Peter Camilleri Dec 18 '18 at 14:56
  • 2
    Perhaps you're looking for [`tap`](https://ruby-doc.org/core-2.5.3/Object.html#method-i-tap) which can be used to avoid the extra `result` after `# do something with result`? There's a good example of this use in my [answer](https://stackoverflow.com/a/47890832/63034) to a different question. – mikej Dec 18 '18 at 15:29
  • @mikej tap is just another version of begin/end block - tap requires the same begin/end block – megas Dec 18 '18 at 21:13
  • Consider [Object#yield_self](http://ruby-doc.org/core-2.5.1/Object.html#method-i-yield_self). – Cary Swoveland Dec 18 '18 at 22:53
  • @megas my comment was mostly about wrapping the `# do something with result` in a `tap` and then avoiding the need for the `result` on the last line of the method. But perhaps I've misunderstood which aspect of the code you'd like to avoid? When you've written _avoid to write construction like this_, can you clarify which bit you'd like to avoid? or maybe give a more concrete example, or an example of how you'd like the code to look if you _could_ do what you wanted? – mikej Dec 19 '18 at 09:47
  • @mikej Thanks for your concern, I'd like to have the same variable like `_`. Maybe Ruby VM can give me this variable. I'm trying to extend Ruby syntax by `load_iseq` https://ruby-doc.org/core-2.5.0/RubyVM/InstructionSequence.html – megas Dec 19 '18 at 10:20
  • maybe update the example in the question with a bit more detail? when you wrote _can I get the result of last expression_ it isn't clear which expression you're referring to or how you'd use it. – mikej Dec 19 '18 at 10:27

0 Answers0