I have an if/else condition, and the if and else sections are identical, save for the operator used. In one case <, and in the other >. Is there a way to conditionally set that operator, to DRY out the code?
if count_year < end_year
while count_year <= end_year
if count_year % 4 == 0
if count_year % 100 != 0
all_years << count_year unless (count_year % 400 == 0)
end
end
count_year += 1
end
puts all_years
elsif count_year > end_year
while count_year >= end_year
if count_year % 4 == 0
if count_year % 100 != 0
all_years << count_year unless (count_year % 400 == 0)
end
end
count_year -= 1
end
puts all_years.reverse
end
This is part of a program for printing out leap years between two given years. I feel like there must be a way to not have to repeat the loop twice. Something like: count_year < end_year ? operator = "<" : operator = ">" – Then using that variable to substitute the operator into a code block or something? Any ideas?
For one small improvement, you can extract really identical parts into a method. Then duplication stops being so massive.
But, the operator substitution…
Yes, there is a way to dynamically choose an operator for evaluation. You see, operators in ruby are just method calls, nothing more. These two lines are equivalent:
And here’s a snippet that chooses random operator for comparison. I leave it up to you to adapt it for your problem (if you want, that is. I advise you against this).