How to stop(avoid) using if and else(conditionals) in Ruby(example)

How to stop(avoid) using if and else(conditionals) in Ruby(example)

Hello guys, when you are working at crowdint.com, one of the most appreciated skills in a developer is when you enjoy to refactor your code all the time and in this little example I’m will share with all of you, about how to stop or avoid using if else conditionals in Ruby, so let’s start.

Before the refactor
class Calculator
  attr_accessor :number_one, :number_two
  def initialize number_one, number_two
    @number_one = number_one
    @number_two = number_two
  end

 def calculate
   if @number_one == 5 and @number_two == 8
     puts "Are equal to 5 and 8: #{@number_one} and #{@number_two}"
   else
     puts "Are different to 5 and 8: #{@number_one} and #{@number_two}"
   end
 end

end
calculator = Calculator.new 5, 8
calculator.calculate

After the refactor
 class Calculator
   attr_accessor :number_one, :number_two
   def initialize number_one, number_two
     @number_one = number_one
     @number_two = number_two
   end

   def calculate
    (conditional && "Are equal to 5 and 8: #{@number_one} and #{@number_two}") ||
     "Are different to 5 and 8: #{@number_one} and #{@number_two}"
   end

   def conditional
     @number_one == 5 && @number_two == 8
   end
 end
 calculator = Calculator.new 4, 8
 puts calculator.calculate

Here we have the output result from console

stop using if else in ruby

stop using if else in ruby

No Comments

Post A Comment