Skip to content

Instantly share code, notes, and snippets.

@RickGriff
Created December 8, 2017 13:52
Show Gist options
  • Save RickGriff/3fcefcc2ee26417c187056120e1d08a7 to your computer and use it in GitHub Desktop.
Save RickGriff/3fcefcc2ee26417c187056120e1d08a7 to your computer and use it in GitHub Desktop.
Solutions to my_array.rb Stretch Challenge
class Array
def my_each(&block)
for i in self
yield i
end
end
def my_map(&block)
arr = []
for i in self
arr << (yield i)
end
arr
end
#I struggled with this one. I was setting self = arr, and getting "Can't change the value of self".
#Solved it using Array#replace, but there is probably a way to do it using more basic Ruby operations.
def my_map!(&block)
arr = []
for i in self
arr << (yield i)
end
#self.replace(arr)
end
def my_each_with_object(obj)
new_obj = obj.class.new
for i in self
yield [i,new_obj]
end
new_obj
end
end
a = [1,2,3]
p a.my_each { |item| puts "THIS IS #{item}"}
p a.my_map { |item| item + 1 } == [2, 3, 4]
b = [1, 2, 3]
b.my_map! { |item| item + 1 }
p b == [2, 3, 4]
c = [1, 2, 3]
d = c.my_each_with_object([]) { |item, obj| obj << { item.to_s => item } }
p d == [{"1"=>1}, {"2"=>2}, {"3"=>3}]
@raderj89
Copy link

raderj89 commented Dec 8, 2017

Nice job! Not surprised you struggle with my_map! as I should have included another method, each_with_index, for you to implement that would have helped you to solve this one without using any of Array's built-in functions.

Here are my solutions - check them out, run them, and let me know if you have any questions:

class Array
  def my_each
    for i in self do
      yield i
    end
  end

  def my_map
    # once you've implemented each_with_object, you can use it here
    self.my_each_with_object([]) do |item, array|
      array << yield(item)
    end
  end

  def my_each_with_index
    index = 0

    # We've implemented each, so we can use it here instead of another for... in... loop here
    self.my_each do |item|
      yield(item, index)
      index += 1
    end
  end

  def my_map!
    # we can't change the reference of self, but we can change the items in self
    self.my_each_with_index { |item, index| self[index] = yield(item) }
  end

  def my_each_with_object(object)
    my_each { |item| yield(item, object) }
  end
end

a = [1,2,3]

p a.my_each { |item| puts "THIS IS #{item}" }

p a.my_map { |item| item + 1 } == [2, 3, 4]

b = [1, 2, 3]

b.my_map! { |item| item + 1 }
p b == [2, 3, 4]

c = [1, 2, 3]

d = c.my_each_with_object([]) { |item, obj| obj << { item.to_s => item } }
p d == [{"1"=>1}, {"2"=>2}, {"3"=>3}]

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