user88
user88

Reputation: 1164

params[...] comparison raises "undefined method `>' for nil:NilClass" error in ruby on rails

I want to check below:

if params[:hidval] > "0"
OR
if !params[:hidval] < "1"

But it gave me error below:

undefined method `>' for nil:NilClass

How do I check above conditions in ruby on rails?

Upvotes: 6

Views: 9000

Answers (4)

David Hempy
David Hempy

Reputation: 6237

Re-reading this question, I realize I missed the mark on my first answer. It side-stepped the problem without addressing it.

The real problem you saw this error is that you probably put ! in the wrong place.

If you meant, if it is not less than "1", then you should write:

if !( params[:hidval] < "1" )

This compares hidval and "1" and THEN negates the result.

What you posted:

if !params[:hidval] < "1"

...first negates hidval (usually resulting in false) and then compares false (or possibly true) to see if it is less than "1". Not only does comparing false to a string not make much sense, you'll actually get you this error:

NoMethodError (undefined method `<' for false:FalseClass)

Upvotes: 0

David Hempy
David Hempy

Reputation: 6237

As of Ruby 2.3, you can use the Safe Navigation Operator &. to streamline this:

irb(main):028:0>   5 > 0
=> true
irb(main):029:0> nil > 0
NoMethodError: undefined method '>' for nil:NilClass
    from (irb):29
irb(main):030:0>   5 &.> 0
=> true
irb(main):031:0> nil &.> 0
=> nil
irb(main):032:0>   5 &.> 99
=> false

This will typically get you what you want (e.g. conditional branching) since nil is falsey. But keep that in mind if you actually depend on an exact false value.

&. means to only call the trailing method if the leading object is not null. It makes a lot more sense in a chained method call like:

user&.deactivate!

But, since the greater-than operator > is actually a method in Ruby, it works here as well.

Personally, I'm not convinced the painful aesthetics of params[:hidval] &.> "0" makes this worthwhile...but that's just a question of style.

Upvotes: 8

Kalpesh Fulpagare
Kalpesh Fulpagare

Reputation: 1299

Try this code

if params[:hidval].present?
  if params[:hidval].to_i > 0
    # Greater than 0 condition
  else
    # Less than equal to 0 condition
  end
end

Upvotes: 2

Sebastian Wramba
Sebastian Wramba

Reputation: 10127

The error message says it all. Make sure, the param actually exists. You try to compare nothing (NilClass) with a number. (which is actually a string, that will be your next problem)

Probably correct would be:

if params[:hidval].present? && params[:hidval] > 0
 # Do something ...
end

Upvotes: 11

Related Questions