28 Aug, 2008

Published at 03:08PM

Tagged with programming, ruby, and tips

This post has 1 comment

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

lobo_tuerto Wednesday, 15 Oct, 2008 Posted at 06:24PM

Excellent, Ruby never ceases to amaze me! :D

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch