On the bright side, we had some time to go over the homework with other students and compare our algorithms, and we exchanged ideas that we had picked up while doing the homework.
One interesting thing I learned from another student was the .tap method, which can be used on all Ruby Objects. Here's an example of how to use it:
HUH??? What's the return value? It turns out that .tap creates a placeholder, feeds that into a block, and returns the placeholder. So it's the same as this:
One interesting thing I learned from another student was the .tap method, which can be used on all Ruby Objects. Here's an example of how to use it:
def return_an_array_of_perfect_squares_up_to_25
[].tap do |squares|
i = 1
while i**2 <= 25
squares << i**2
i += 1
end
end
end
def return_an_array_of_perfect_squares_up_to_25
squares = []
i = 1
while i**2 <= 25
squares << i**2
i += 1
end
squares
end
Possibly a bit more confusing, which is why I'm hesitant to use it in my own code, but it is a bit more concise, which is nice. And it gives an excuse to indent!
NOTE: Example provided for illustration purposes only. If I were programming this for real, this is how I would do it:
def return_an_array_of_perfect_squares_up_to_25
(1..Math.sqrt(25)).map{|num| num**2}
end
And of course, that's the power of map/collect and select! \(^○^)/
Skills developed: Extracting data from Arrays/Hashes, iterating over Arrays/Hashes
QOTD: "When you don’t create things, you become defined by your tastes rather than ability. Your tastes only narrow and exclude people. So create." - why the lucky stiff, author of why's (poignant) guide to ruby
Skills developed: Extracting data from Arrays/Hashes, iterating over Arrays/Hashes
QOTD: "When you don’t create things, you become defined by your tastes rather than ability. Your tastes only narrow and exclude people. So create." - why the lucky stiff, author of why's (poignant) guide to ruby
No comments:
Post a Comment