Krishnaswamy Subramanian

Kirukkalgal - gist on my random thoughts

Ruby: Tap

| Comments

When I first saw Ruby 1.9 new method Object#tap I slightly overlooked it and felt that this method may not be useful. But recently in one of my project I realized that how it can improve the reability of the code and avoids un-necessary return statements.

student.rb
1
2
3
4
5
6
7
8
9
10
class Student
  attr_accessor :name, :age, :std
  def initialize name, age, std
      @name, @age, @std = [name, age, std]
  end

  def to_s
      "#{@name} #{@age} #{@std}"
  end
end

If we want to print and return the student object after creating it, without tap the code will look like:

without_tap.rb
1
2
3
4
5
6
7
class StudentFactory
  def self.create_student(name, age, std)
      student = Student.new(name, age, std)
      p student.to_s
      student
  end
end

The same can be made more readable and prettier with the help of tap

with_tap.rb
1
2
3
4
5
class StudentFactory
  def self.create_student(name, age, std)
      Student.new(name, age, std).tap { |student| p student.to_s }
  end
end

Comments