Created
January 17, 2017 19:52
-
-
Save carlweis/7a5d7ad036e12ed51f379268723688d1 to your computer and use it in GitHub Desktop.
Ruby methods for interview process.
This file contains hidden or 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
# method 1 | |
# returns members of the Fibonacci series up to a certain value | |
def method_one(max) | |
i1, i2 = 1, 1 | |
while i1 <= max | |
yield i1 | |
i1, i2 = i2, i1+i2 | |
end | |
end | |
method_one(100) {|f| print f, " " } | |
# expected output | |
# 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 | |
# method 2 | |
# helper method on the Integer class that generates a stream of integers | |
def Integer.all | |
Enumerator.new do |yielder, n: 0| | |
loop { yielder.yield(n += 1) } | |
end.lazy | |
end | |
p Integer.all.first(10) | |
# expected output | |
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
# Now how would you get the first 10 multiples of three? | |
p Integer.all.select {|i| (i % 3).zero? }.first(10) | |
# expected output | |
# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] | |
# multiples of three whose string representations are palindromes | |
def method_three?(n) | |
n = n.to_s | |
n == n.reverse | |
end | |
p Integer.all.select{|i| (i % 3).zero?}.select{|i| palindrome?(i)}.first(10) | |
# expected output | |
# [3, 6, 9, 33, 66, 99, 111, 141, 171, 222] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment