I have not spent any time with Hanami, but I am hoping to change that.
I like Sinatra when your goal is to respond to requests and do not need the full Rails functionality and ecosystem.
Hanami looks like it fits somewhere between the two.
I have not spent any time with Hanami, but I am hoping to change that.
I like Sinatra when your goal is to respond to requests and do not need the full Rails functionality and ecosystem.
Hanami looks like it fits somewhere between the two.
We needed to find duplicate characters in multiple arrays for Saturday’s Advent of Code.
In the first part of the problem, it was among two arrays, so I did something quick like this:
first_array.select { |char| second_array.include?(char) }
This worked as expected, but in part 2, you needed to perform a similar search across three arrays.
I could have chained a second select
or duplicated the line entirely, but I figured there was a more straightforward way…and of course, in Ruby, there is almost always a more straightforward way.
I do not have a traditional comp sci background, so my mind rarely jumps to Bitwise operators, but in this case, this is the Bitwise &
operator is exactly what we needed.
@scott pointed this is not Bitwise when dealing with strings:
It is the unary and operator. On arrays, #& is a method that returns the set union of two arrays. On integers, it is indeed implemented as a bitwise and.
a = "vJrwpWtwJgWrhcsFMMfFFhFp".chars
b = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL".chars
c = "PmmdzqPrVvPwwTWBwg".chars
duplicates = a & b & c
Even better, this easily scales across N arrays.
I have not had much use for Sizzy in while, but fired it up today and was instantly re-impressed. One of the more indispensable tools for frontend web development.
If I were deploying this somewhere, I would lean towards something that looks more like the readable_solution
below.
But for the sake of the challenge:
def solution(number)
"#{"Fizz" if (number % 3).zero?}#{"Buzz" if (number % 5).zero?}"
end
raise unless solution(3) == "Fizz"
raise unless solution(5) == "Buzz"
raise unless solution(15) == "FizzBuzz"
puts "It works!"
If this were a one-liner competition, I would like my chances. 😄
def readable_solution(number)
modulo_3 = (number % 3).zero?
modulo_5 = (number % 5).zero?
if modulo_3 && modulo_5
"FizzBuzz"
elsif modulo_3
"Fizz"
elsif modulo_5
"Buzz"
end
end