Home > Back-end >  Checking an array is nil? or not, using proc in ruby
Checking an array is nil? or not, using proc in ruby

Time:05-17

I'm trying to solve this assignment:

Create a proc that will check whether a given array of elements are nil or not. Use .nil? to evaluate elements. Print 'true' if the elements are nil and 'false' if the elements has a value?

This is my attempt:

   def check_nill(array1)
      p = Proc.new {|x| x.nil?}
      res= p.call(array1)
      if res == true
        return "true"  
      else  
        return "false"  
      end 
   end
   
   array1=[{},nil,[]]
   result=check_nill(array1)
   puts "#{result}"

Here actually, the output should be "true". But this code gives "false" as output. Can someone tell, what is the reason?

CodePudding user response:

Your method currently checks whether the given object is nil:

check_nill(nil) #=> "true"
check_nill([])  #=> "false"
check_nill(123) #=> "false"

Note that this object can be anything, so your argument name array1 is somehow misleading for this use case. (you might also want to rename the method to check_nil, i.e. with one l)

Here actually, the output should be "true" [...]

I assume that you actually want to check whether any of the array's elements meets a condition, i.e. if the array contains nil. You can use any? with a block for this. From within the block, you can call your proc:

prc = Proc.new { |x| x.nil? }
[{}, nil, []].any? { |element| prc.call(element) }
#=> true

Which can be shortened by converting the proc to a block:

prc = Proc.new { |x| x.nil? }
[{}, nil, []].any?(&prc)
#=> true

You can even get rid of your custom proc and use Symbol#to_proc instead:

[{}, nil, []].any?(&:nil?)
#=> true

There's also all? which checks whether all elements meet the condition, e.g.:

[{}, nil, []].all?(&:nil?)
#=> false

[nil, nil, nil].all?(&:nil?)
#=> true

CodePudding user response:

If I understand the question correctly, you are trying to check whether all the array elements are nil/blank/false or not. If there is any non-nil value present in the array, you want to return true, else false. Here is how you can determine this:

array1 = [{}, nil, []]
array1.all?(&:blank?) # this returns true

array2 = [{}, nil, [], 1]
array1.all?(&:blank?) # this returns false

CodePudding user response:

[nil,nil,nil].all? nil No proc.

  • Related