简体   繁体   中英

Ruby class method behaviour

Consider below chunk of code:

class A
  def self.a(b)
    if b > 0
      b * b
    end
  end
end

Now calling method a as below:

2.3.0 :015 > A.a(2)
 => 4 
2.3.0 :016 > A.a(0)
 => nil

Why nil on passing 0 as argument?

You should modify your method if you want to return anything else but nil as @cary-swoveland mentioned like:

class A
  def self.a(b)
    if b > 0
      b * b
    else
      puts 'Calculation not possible'
      # or whatever you want your method to return
    end
 end
end

Additionally, you can modify your conditional to if b >=0 if you want it to work for zero

All ruby methods return last statement/expression by default, if there is no return mentioned previously. So, in your case,

A.a(0) #Last statement executed end, as 0 > 0 is false, without going in if. SO, it returns nothing, in other words null/nil.

As specified by @dstrants, you can add else to see some output or you can do as follows (no need of else clause),

class A
  def self.a(b)
    if b > 0
      return b * b
    end
    return "Value <= 0"
  end
end

This will result in output other than nil .

ps Don't use static methods( self methods), until you absolutely want to!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM