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 areniland 'false' if the element has a [truthy] value.
This is my attempt:
def check_nil(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_nil(array1)
puts "#{result}"
Here actually, the output should be "true" but this code gives "false" as output. Can someone explain the reason?
Your method currently checks whether the given object is
nil:Note that this object can be anything, so your argument name
array1is somehow misleading for this use case. (you might also want to rename the method tocheck_nil, i.e. with onel)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 useany?with a block for this. From within the block, you can call your proc:Which can be shortened by converting the proc to a block:
You can even get rid of your custom proc and use
Symbol#to_procinstead:There's also
all?which checks whether all elements meet the condition, e.g.: