LoginSignup
47
44

More than 5 years have passed since last update.

tap

Last updated at Posted at 2012-04-11

配列を変更する

p [].tap{|arr|
  5.times.each do|i|
    arr << i
  end 
} 
# 出力
# [0, 1, 2, 3, 4]

文字列を変更する

p 'a'.tap{|str|
  str << 'b' 
}
# 出力 
# ab

ActiveRecord を覗く

便利!

a = Foo.where(bar:'a').tap{|a| p a.to_sql}.all

配列の中身を見る

[1, 2, 3].tap{|a| p a }.push(4).tap{|a| p a }
# 出力
# [1, 2, 3]
# [1, 2, 3, 4]

ちょっとかっこいい

def foo
  a = []
  5.times.each{|i|
    a << i
  }
  a
end

上が下のように書ける。初期化とリターンがいらないけれど特に読みやすくないのでやっぱりあまりかっこよくないかもしれない。

def foo
  [].tap{|a|
    5.times.each{|i|
      a << i
    }
  }
end
47
44
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
44