Skip to content

Instantly share code, notes, and snippets.

@ldanz
Created September 29, 2014 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldanz/3658322c76afb9c06653 to your computer and use it in GitHub Desktop.
Save ldanz/3658322c76afb9c06653 to your computer and use it in GitHub Desktop.
module FakeEnumerable
def map
res = []
each do |item|
res << yield(item)
end
res
end
def select
res = []
each do |item|
res << item if yield(item)
end
res
end
def sort_by(&block)
temp_array = []
each do |item|
temp_array << [item, yield(item)]
end
temp_array.sort_by { |x, y| y }.map { |x, y| x }
end
def reduce(*args, &block)
initial_given = false
sym_given = false
acc, sym = case args.size
when 0
raise LocalJumpError unless block_given?
[nil, nil]
when 1
if block_given?
initial_given = true
[args.first, nil]
else
sym_given = true
[nil, args.first]
end
when 2
initial_given = true
sym_given = true
args
end
transformation = ->(acc, elt) { acc.send(sym, elt) } if sym_given
first_pass = true
each do |item|
acc =
if first_pass && !initial_given
item
else
if sym_given
transformation.call(acc, item)
else
yield(acc, item)
end
end
first_pass = false
end
acc
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment