[Ruby] [Ruby] If statement problem

1 minute read

Background

When I solved the problem of Ruby, I was disappointed at my answer because of the smartness of the model answer, so I left it as a memorandum because :confounded:.

Problem

Enter a positive integer. That integer is The difference from a multiple of 10 (10,20,30…) True if within 2 Otherwise, let’s create a method that outputs False.

Sample output: near_ten(12) → True near_ten(17) → False near_ten(19) → True

My answer

Ruby


def near_ten(num)
  if num %10 <= 2
    puts "True"
  elsif num %10 >= 8
    puts "True"
  else
    puts "False"
  end
end

Model answer

Ruby


def near_ten(num)
  quotient = num %10
  if quotient <= 2 || quotient >= 8
    puts "True"
  else
    puts "False"
  end
end

Impression

When I saw the model answer, I shouted in my heart that it was too smart and too smart. (I can’t say it because it’s on the road: unamused:)

Certainly, it is easy to forget the existence of “**   **” which corresponds to or. .. .. ..

To be honest, the code is correct answer: sparkles:, but I felt again that the coolness oozes out depending on how smart: star2: is written. .. ..

Refactoring Easy to work hard. .. ..

Tags:

Updated: