Skip to content

Instantly share code, notes, and snippets.

@SoxFace
Last active October 10, 2019 10:20
Show Gist options
  • Save SoxFace/adfc8bbfda8c4f06a6386a767af8c1d3 to your computer and use it in GitHub Desktop.
Save SoxFace/adfc8bbfda8c4f06a6386a767af8c1d3 to your computer and use it in GitHub Desktop.
Riddle me Gabe
def example(a) # function a
b = [] # b is an empty array
for i in 0..a # for every (i)ndex in the range 0 to a (or 4 in this example)
b[i] = i # not clear how this works. I think it's a shorthand for .push
# More importantly, I don't know why you have to assign the position of the index in the array to i
end # end of loop
return b #return b
end # end of function
example(4) # calls a, loops, pushes 0, 1, 2, 3, 4 into the array b
# => [0, 1, 2, 3, 4]
# 1) write the same thing but replace that logic using ruby each method
# 2) write the same thing but avoid modifying the array, hint: use map
# hint: (0..a).each { |i| ... } and (0..a).map { |i| ... }
# https://www.rubyguides.com/2018/10/ruby-map-method/
# 1) using each
def exampleEach(a)
b = []
(0..a).each { |i|
b[i] = i
}
return b
end
# 2) using map
def exampleEach(a)
b = []
(0..a).map { |i|
b[i] = i
}
end
@SoxFace
Copy link
Author

SoxFace commented Oct 10, 2019

Feedback

for map there is a an error which doesn't satisfy the condition of the problem, the problem was
2) write the same thing but avoid modifying the array
b used to be [ ] and now it's [0,1,2,3,4]. Let me modify the statement a bit:

  • write the same thing but avoid modifying the array, the function needs to return [0,1,2,3,4] but b needs to end up being [ ] (edited)
    you can run irb locally and do the following to verify that:
def exampleEach(a)
  b = []
  
  new_b = (0..a).map { |i|
                   b[i] = i
                }
  puts b
  return new_b
end

Resources

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