LoginSignup
2
2

More than 5 years have passed since last update.

#mapのチェーンを逆にする

Posted at

関数をメソッドチェーンするとなんかみっともない時があるので、逆にしたくなる。

具体的には

[1] pry(main)> [1,2,3].map {|x| x * 2 }
=> [2, 4, 6]

はHaskellだと

λ map (*2) [1,2,3]
[2,4,6]

こう書ける。こんな感じにしたい。ちょっとやってみたらできた。

class Pipe
  attr_accessor :receiver

  def initialize(thunk)
    @thunk = thunk
  end

  def self.map &block
    self.new lambda { |h| h.receiver.map &block }
  end

  def receive receiver
    @receiver = receiver
    self.instance_eval &@thunk
  end
  alias_method :<<, :receive

end

one = Pipe.map {|x| x * 2} << [1,2,3]
p one # => [2,4,6]

two = Pipe.map(&:reverse).receive Pipe.map(&:upcase).receive ["foo", "bar", "baz"]
p two # => ["OOF", "RAB", "ZAB"]

しかしこれはPipeなのか?

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