Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compose (*) function work in Ruby (from The Ruby Programming Language)?

Excerpt The Ruby Programming Language:

module Functional
  def compose(f)
    if self.respond_to?(:arity) && self.arity == 1
      lambda {|*args| self[f[*args]] }
    else
      lambda {|*args| self[*f[*args]] }
    end
  end
  alias * compose
end

class Proc; include Functional; end
class Method; include Functional; end

f = lambda {|x| x * 2 }
g = lambda {|x, y| x * y}
(f*g)[2, 3] # => 12

What is the difference between f and *f in the if/else clause?

like image 240
Dan Jenson Avatar asked Feb 03 '26 14:02

Dan Jenson


1 Answers

The * either collects all the items into an array, or explodes an array into individual elements--depending on the context.

If args = [1, 2, 3], then:

  • f[args] is equivalent to f[ [1, 2, 3] ] #There is one argument: an array.
  • f[*args] is equivalent to f[1, 2, 3] #There are three arguments.

If f[*args] returns [4, 5, 6], then:

  • self[f[*args]] is equivalent to self[ [4, 5, 6] ] #self is called with 1 arg.
  • self[*f[*args]] is equivalent to self[4, 5, 6] #self is called with 3 args.

An example of * being used to collect items into an Array is:

  • lambda {|*args| ....}

You can call that function with any number of arguments, and all the arguments will be collected into an array and assigned to the parameter variable args.

like image 148
7stud Avatar answered Feb 05 '26 06:02

7stud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!