Skip to content

Opposites Attract (Ruby Fundamentals)

Posted on:May 16, 2022 at 09:50 AM

Image

Question

Link to question

Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren’t.

My thought process

  1. I want the solution to be very simple, probably one line, that seems to be possible since I can already imagine using modulo or some technique that organises even and odd numbers

  2. A step further is to think of how even and odd numbers bouce off each other, a list of the behaviours include;

The last two are the most important to our solution.https://bigmachine.io/theory/mod-and-remainder-are-not-the-same

  1. Our soltution should also handle negative numbers, its important to be careful how to use mod and remainder

Test suite

describe "Basic Tests" do
  it "should pass basic tests" do
    Test.assert_equals(lovefunc(1,-4), true)
    Test.assert_equals(lovefunc(2,-2), false)
    Test.assert_equals(lovefunc(0,1), true)
    Test.assert_equals(lovefunc(0,0), false)
    Test.assert_equals(lovefunc(5,5), false)
  end
end

Solution

def lovefunc( flower1, flower2 )
  (flower1 + flower2) % 2 != 0
end

Other solutions I like:

def lovefunc(*all_flowers)
     all_flowers.sum.odd?
end

We are using the parameter behaviour of the language itself here.

.odd? can replace the % 2 != 0 section of my code as so

def lovefunc( flower1, flower2)
  (flower1 + flower2).odd?
end

This was my first solution but I did not want to use a language specific method