LoginSignup
1
1

More than 3 years have passed since last update.

injectメソッドについて

Posted at

現在チェリー本やってます。

その中ででてきた表題の件に関して整理しておきます。

まず、大前提として、to_hexメソッドのリファクタリングの話です。

3段階のリファクタリングで、
①そのまんまのコード
②eachメドレー
③injectメソッドという流れ。

ではまず最初のコードがこちら

def to_hex(r,g,b)
 "#"+
  r.to_s(16).rjust(2,"0")+
  g.to_s(16).rjust(2,"0")+
  b.to_s(16).rjust(2,"0")
end

rgbを16進数の2文字ずつに変換している感じです。

injectメソッドはeachやmapなどと同様に繰り返し処理のメソッドである。

配列.inject(初期値の最初の値) {|初期値, 要素| ブロック処理 }

eachメソッドをより短くすることができることがある。

def to_hex(r,g,b)
  hex="#"
  [r,g,b].each do|n|
  hex+=n.to_s(16).rjust(2,"0")
  end
  hex
end

上記を

def to_hex(r,g,b)
  [r,g,b].inject("#")do|hex,n|
  hex+n.to_s(16).rjust(2,"0")
  end
end

にできる。

はい。こんな感じでしょうか。

以上。

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