Created
December 8, 2017 13:52
-
-
Save RickGriff/3fcefcc2ee26417c187056120e1d08a7 to your computer and use it in GitHub Desktop.
Solutions to my_array.rb Stretch Challenge
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
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}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: