2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

zip_with

Last updated at Posted at 2012-10-15

Ruby の Array#zip はブロックを取れますが,戻り値は nil となっているため,Haskell の zipWith のような処理はできません.探してみましたがそれっぽいのは無いので自作してモンキーパッチを当てることにしました.

zip_with
class Array
  def zip_with *args
    if block_given?
      self.zip(*args).map{|a| yield *a}
    else
      self.zip(*args).map
    end
  end
end

これで,下記のように zip_with を使えます.

a = 1, 2, 3
b = 1.0, 2.0, 3.0
c = 'a', 'b', 'c'
a.zip_with(b, c){|i,j,k| (i*j).to_s + k } # => ["1.0a", "4.0b", "9.0c"]

ブロックを与えなかった場合の挙動がこれで良いのかよく分かっていないですが,とりあえずこんな感じに.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?