DEV Community

loading...

Discussion on: Daily Challenge #299 - Time to Grille!

Collapse
biancapower profile image
Bianca Power

ruby

def grille(message, code)
  output = ""

  # convert code to binary
  binary_code = code.to_s(2)

  # prepend the appropriate number of zeros to match length of message
  while message.length > binary_code.length
    binary_code.prepend('0')
  end

  # combine messages and binary_code into a hash
  arrays_hash = Hash[message.split("").zip(binary_code.split(""))]

  # if the value is 1, add the key to the output string
  arrays_hash.each do |k, v|
    if v == "1"
      output << k
    end
  end

  return output
end
Enter fullscreen mode Exit fullscreen mode
Collapse
citizen428 profile image
Michael Kohl

Ruby allows string interpolation in format strings, which makes generating binary_code easier:

binary_code = "%0#{message.length}d" % code.to_s(2)
Enter fullscreen mode Exit fullscreen mode

Ruby 2.7 also added a handy filter_map method, which can simplify the second half of your method:

message.chars.zip(binary_code.chars).filter_map { |c, i| c if i == "1" }
Enter fullscreen mode Exit fullscreen mode