Created
July 7, 2011 14:02
-
-
Save melborne/1069573 to your computer and use it in GitHub Desktop.
Haskell-like Arithmetic Sequence in Ruby
This file contains 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
# encoding: UTF-8 | |
class Array | |
alias __eq__ === | |
def ===(other) | |
if self.size == other.size and any? { |item| item.instance_of? Class } | |
other = other.to_enum | |
return all? { |item| item === other.next } | |
end | |
__eq__(other) | |
end | |
alias __to_a__ to_a | |
def to_a(decimal=1) | |
if [Object, Range] === self | |
n, range = self | |
dist = range.begin - n | |
res = Enumerator.new { |y| loop { y << n; n += dist } } | |
unless range.end.to_s.to_i < 0 | |
return res.take_while { |i| i <= range.end } | |
.map { |i| i.to_i(decimal) rescue i } | |
else | |
return res | |
end | |
end | |
__to_a__ | |
end | |
end | |
class Float | |
alias __to_i__ to_i | |
def to_i(n=0) | |
n > 0 ? (self*10**n).__to_i__/10.0**n : __to_i__ | |
end | |
end | |
class String | |
alias __plus__ + | |
def +(other) | |
if other.is_a? Integer | |
return (self.ord + other).chr | |
end | |
__plus__(other) | |
end | |
def -(other) | |
case other | |
when String | |
self.ord - other.ord | |
when Integer | |
(self.ord - other).chr | |
else | |
raise ArgumentError | |
end | |
end | |
end | |
[1,2,3,4].to_a # => [1, 2, 3, 4] | |
[1..10].to_a # => [1..10] | |
[1, 3..10].to_a # => [1, 3, 5, 7, 9] | |
[0, 5..50].to_a # => [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50] | |
[1.1, 2.3..10].to_a # => [1.1, 2.3, 3.4, 4.6, 5.8, 7.0, 8.2, 9.4] | |
[1.11, 2.32..10].to_a(2) # => [1.11, 2.31, 3.52, 4.73, 5.94, 7.15, 8.36, 9.57] | |
['a', 'c'..'m'].to_a # => ["a", "c", "e", "g", "i", "k", "m"] | |
['A', 'I'..'z'].to_a # => ["A", "I", "Q", "Y", "a", "i", "q", "y"] | |
[1, 9..-1].to_a.take 20 # => [1, 9, 17, 25, 33, 41, 49, 57, 65, 73, 81, 89, 97, 105, 113, 121, 129, 137, 145, 153] | |
['A', 'D'..'-1'].to_a.take 20 # => ["A", "D", "G", "J", "M", "P", "S", "V", "Y", "\\", "_", "b", "e", "h", "k", "n", "q", "t", "w", "z"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment