Varinder Sohal
Varinder Sohal

Reputation: 1292

How to check value null in ruby on rails 3?

I have create new array jobs and j.id is start from 423 and loop creates array index from 0 to total job ids with null value from 0 to 422 id. So my question is how to set condition to check the null value of j.name?

@jobs = []
demo.demojobs.each do | j |
    if j.name != null #condition 
        @jobs[j.id] = j.name
    end
end 

I am working on rails version 3.2.11

Output:

pipe
0: null
1: null
.
.
.
.
423:    "jobname"
424:    "jobname"
425:    "jobname"
426:    "jobname"
427:    "jobname"

Upvotes: 1

Views: 2357

Answers (4)

Tanay Sharma
Tanay Sharma

Reputation: 1164

how to set condition to check the null value of j.name?

There are many ways to check for null/nil or an empty string in ruby

  1. present? This will return true or false

    j.name.present?
    
  2. blank? This is opposite of present?

    j.name.blank?
    
  3. j.name == nil

  4. empty? can be used on strings, arrays and hashes.

Edit:

@jobs = {}
#in your loop
@jobs[j.id] = j.name if j.name #you can use any condition here to check nil

Upvotes: 1

mrzasa
mrzasa

Reputation: 23327

nil value is interpreted as false in conditions, so you can write:

@jobs = []
demo.demojobs.each do | j |
    if j.name 
        @jobs[j.id] = j.name
    end
end 

or in a more concise manner:

@jobs = []
demo.demojobs.each do | j |         
  @jobs[j.id] = j.name if j.name
end 

You can also use #nil? method if you want to check explicitly:

@jobs = []
demo.demojobs.each do | j |
    if !j.nil? 
        @jobs[j.id] = j.name
    end
end 

There is a nice blogpost explaining various options: https://blog.arkency.com/2017/07/nil-empty-blank-ruby-rails-difference/

Upvotes: 2

Umar Khan
Umar Khan

Reputation: 1430

it's nil in Ruby, not null You can check if an object is nil by calling present? or blank?.

j.name.present?

this will return false if the name is an empty string or nil .

or you can use

j.name.blank?

Upvotes: 1

Milind Patel
Milind Patel

Reputation: 19

You can use present? or blank? in condition. Your code should be

if j.name.present? #condition 
   @jobs[j.id] = j.name
end

Upvotes: 0

Related Questions