LoginSignup
14
14

More than 5 years have passed since last update.

最近思いついたRubyのObject.itselfの使用方法

Posted at

Object.itselfはRuby 2.2で公開されたメソッド、名前のとおりオブジエクト自身を返すいわゆるIdentity Functionです。

何でこんなものが必要かというと、例えばgroup_byを使って文を文字ごとに分けたいときとか:

"hello world".chars.group_by(&:itself) 
=> {"h"=>["h"], "e"=>["e"], "l"=>["l", "l", "l"], "o"=>["o", "o"], " "=>[" "], "w"=>["w"], "r"=>["r"], "d"=>["d"]}
"hello world".chars.group_by(&:itself).map{|k,v| [k,v.count]}.to_h
=> {"h"=>1, "e"=>1, "l"=>3, "o"=>2, " "=>1, "w"=>1, "r"=>1, "d"=>1}

等が出来ます。

意味は無いですがArray.flattenの代わりにこんなこととか:

[[1,2], [3,4]].flat_map(&:itself)
=> [1, 2, 3, 4]

遊んでみると結構面白いメソッドですね。

14
14
0

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
14
14