-2

I found following code at the internet

class Test
  def value
    'string'
  end

  def inspect
    'value'
  end
end

def test(arg)
  arg.tap { |i| i.value }
end

p test(Test.new)

Could anyone explain why it returns

p test(Test.new) 
# >> value
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user2322409
  • 814
  • 9
  • 15

2 Answers2

1

Because arg.tap returns arg itself, and p prints arg.inspect, since you have overwritten theinspect method of Test, it returns a string 'value', so you the print result is value

see also:
- p vs puts in Ruby
- tap method

mikej
  • 65,295
  • 17
  • 152
  • 131
Fangxing
  • 5,716
  • 2
  • 49
  • 53
1

tap used for chain of methods. It runs the passed blocked and returns the input without any change.

It means

arg.tap { |i| i.value } will return arg

p method runs inspect method of passed object

Mohsen Alizadeh
  • 1,595
  • 12
  • 25