Reputation: 1292
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
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
present? This will return true or false
j.name.present?
blank? This is opposite of present?
j.name.blank?
j.name == nil
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
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
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
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