Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4ruby-on-rails-5

How to use correctly def with if..else statements in ruby?


I started learning ruby, for this moment I understand how to create class objects, and how to write very simple IF..ELSE statement. But how to write correctly def with IF..ELSE statement? Help please with advice how to write it correctly?

   #I can write simple statement like this 

number = 1
if number == 1
    number += 1
    puts "the number is #{number}"
else 
    puts "number is more then 2"
end

#But then i want to write something like this 

class Maths
  def initialize(number_id)
    @number = number_id 
  end 

  def numberdata()
    if @number == 1 
      @number +=1
      puts "the number is #@number"
    else 
      puts "number is greater than 3"
    end
  end
end

classob5 = Maths.new("1")
classob5.numberdata()

I expected the output from the second part to be "the number is 2", but the actual output turned out to be "number is greater than 3" Please help with advice about how to write it correctly.


Solution

  • The error here is that the Maths class is initiated with a String instead of an Integer in the line classob5 = Maths.new("1").

    So, what happens is, when numberdata() is invoked, it compares @number whose value is "1"(String) with 1, which is an Integer. Thus, the if condition fails, since they are not equal, and you get the result from the else condition.

    The usage of if..else is absolutely correct. The class object just needs to be instantiated as classob5 = Maths.new(1).