Tapping into Ruby expressions

Raise your hand if you’ve done something like this before:

1
2
3
4
5
def determine_something
  val = get_the_first_thing
  p val
  val + get_the_second_thing
end

Don’t lie, you know you have. The idea is that you need to see what is in the “first thing” before moving on. You know, the lazy man’s debugging. But it completely tears up that implementation. It turned that little bit of simple math into 3 lines of stuff plus an extra variable, just to check the “first thing”!

Well, I stumbled onto a much easier way (This is Ruby, remember?) that I just hadn’t thought of before. To keep consistent with where I found this, we’ll call this method tap.

1
2
3
4
5
6
class Object
  def tap
    yield self
    self
  end
end

Redoing the determine_something method using Object#tap, we have:

1
2
3
def determine_something
  get_the_first_thing.tap { |r| p r } + get_the_second_thing
end

Pretty sweet. See the source for more examples.

Update: A more extensible version of Object#tap...

1
2
3
4
5
6
7
8
9
10
class Object
  def tap
    if block_given?
      yield self
    else
      p self
    end
    self
  end
end

Then if you only want to “p” the value, just “tap” into it without a block. The determine_something method then becomes:

1
2
3
def determine_something
  get_the_first_thing.tap + get_the_second_thing
end

And the block option is there if you need it.

Comments

01

lobo_tuerto on Wed Oct 15 at 06:24PM

Excellent, Ruby never ceases to amaze me! :D

Have something to say?
Please rewrite the image text Are You Human? Hint: Are You Human? Formatting Tips

or

© 2008 Ryan Heath | Site Management A Ruby on Rails production.

Get in Touch