2024-08-29

 29 Aug 2024

Return a string that alternates between Loves Me and Loves Me Not

Taken from Sloth Bytes

Given a number of petals, return a string which repeats the phrases Loves me and Loves me not for every alternating petal, and return the last phrase in all caps.

Remember to put a comma and space between phrases.

Solution

This is the answer I came up with:

def loves_me(num)
  result = []
  last = num - 1
     
  num.times { |time|
    if time.even?
      result << "Loves me"
    else
      result << "Loves me not"
    end
    }
  
  result[last] = result[last].upcase
  return result.join(", ")
end

Testing

Solution tested in REPL:

https://try.ruby-lang.org/playground/#code=def+loves_me(num)%0A++result+%3D+%5B%5D%0A++last+%3D+num+-+1%0A+++++%0A++num.times+%7B+%7Ctime%7C%0A++++if+time.even%3F%0A++++++result+%3C%3C+%22Loves+me%22%0A++++else%0A++++++result+%3C%3C+%22Loves+me+not%22%0A++++end%0A++++%7D%0A++%0A++result%5Blast%5D+%3D+result%5Blast%5D.upcase%0A++return+result.join(%22%2C+%22)%0Aend%0A%0A%23+%22Loves+me%2C+Loves+me+not%2C+LOVES+ME%22%0Aloves_me(3)&engine=cruby-3.2.0

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems