Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created March 18, 2012 20:30
Show Gist options
  • Save peterhellberg/2081118 to your computer and use it in GitHub Desktop.
Save peterhellberg/2081118 to your computer and use it in GitHub Desktop.
Support for multiple return values in Ruby 1.9, the way Common Lisp does it… sort of
class MultiValue < BasicObject
attr_reader :secondary
def initialize(obj, *secondary)
@obj, @secondary = obj, secondary
end
def method_missing(sym, *args, &block)
@obj.__send__(sym, *args, &block)
end
end
class Array
def to_mv
MultiValue.new(*self) unless empty?
end
end
class Numeric
def floor_with_remainder
[floor, remainder(floor)].to_mv
end
end
@peterhellberg
Copy link
Author

Common Lisp functions can return multiple values:

(floor pi)
; 3 ;
; 0.14159265358979323851L0

Conveniently, functions that return multiple values are treated,
by default, as though only the first value was returned:

(+ (floor pi) 2)
; => 5

Now we can do the following in Ruby:

Math::PI.floor_with_remainder + 2
# => 5

mv = Math::PI.floor_with_remainder
mv.secondary.inject(mv, :+)
# => 3.141592653589793

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment