DEV Community

Cover image for Ruby vs Elixir - FizzBuzz

Ruby vs Elixir - FizzBuzz

Josh Hadik on February 01, 2019

I've been working through a lot of common interview questions recently as part of my daily reps, something I do everyday to force me to learn const...
Collapse
 
art4ride profile image
Vladimir • Edited

Nice article, thanks for sharing! Quick suggestion:

You can get to pattern matching power in this place:

  defp get_fizz_buzz_value(num) do
    cond do
      rem(num, 15) == 0 -> "FizzBuzz"
      rem(num, 3) == 0 -> "Fizz"
      rem(num, 5) == 0 -> "Buzz"
      true -> to_string(num)
    end
  end
Enter fullscreen mode Exit fullscreen mode

->

  defp get_fizz_buzz_value(num) when rem(num, 15) == 0, do: "FizzBuzz"
  defp get_fizz_buzz_value(num) when rem(num, 3) == 0, do: "Fizz"
  defp get_fizz_buzz_value(num) when rem(num, 5) == 0, do: "Buzz"
  defp get_fizz_buzz_value(num), do: to_string(num)
Enter fullscreen mode Exit fullscreen mode

Might be even nicer to skip rem(,15) in favor of rem(,3) and 5 together separately, but it will also affect the Ruby code then

Collapse
 
joshhadik profile image
Josh Hadik

I like this... a lot!

Collapse
 
jeffweiss profile image
Jeff Weiss

Equivalent-ish, Elixir code golf solution:

1..31|>Enum.map(fn n when rem(n,15)==0->"FizzBuzz";n when rem(n,3)==0->"Fizz";n when rem(n,5)==0->"Buzz";n->n end)|>IO.inspect
Collapse
 
joshhadik profile image
Josh Hadik

Haha always love a good one liner!