Created
March 18, 2012 20:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Common Lisp functions can return multiple values:
Conveniently, functions that return multiple values are treated,
by default, as though only the first value was returned:
Now we can do the following in Ruby: