mardi 2 mai 2017

Nested if then statements in Ruby

I'm at the beginning of a programming bootcamp and am stuck on a practice problem (sigh).

I'm supposed to "define a method, three_digit_format(n), that accepts an integer, n, as an argument. Assume that n < 1000. Your method should return a string version of n, but with leading zeros such that the string is always 3 characters long."

I have been tinkering with versions of the below code, but I always get errors. Can anyone advise?

def three_digit_format(n)
stringed = n.to_s
stringed.size
if stringed.size > 2
  return stringed
end
elsif stringed > 1
  return "0" + stringed
end
else 
  return "00" + stringed
end
end
puts three_digit_format(9)

Aucun commentaire:

Enregistrer un commentaire