problem: Create a Proc p that will check whether a given array of elements are nil or not. Use .nil? to evaluate elements. Print 'true' if elements are nil, and 'false' if the elements has a value
Issue: I came up with below solution but its giving me only one value as true instead of checking for each value of array , please help in correcting below code:
Code:
def check_nill(array1)
p = Proc.new{ |num| num.nil?}
c = array1.any?(&p)
return c
end
array1 = [2,nil,8]
result = check_nill(array1)
puts "#{ result1 }"
Output: true
CodePudding user response:
Create a Proc to check if a value is a nil or not.
my_proc = Proc.new { |num| num.nil? }
Iterate over the array using the above proc
array1 = [2,nil,8]
array1.map { |x| my_proc.call(x) }
You will get the below result
[false, true, false]
CodePudding user response:
Your solution doesn't work because the method you're using, Array#any?
, returns true if any of the values in the array is nil
(due to your p
). What I understood is that you want a solution that will return if each element is nil
or not.
A possible solution is:
# You can create a Proc `p` that'll map an array to the results of `nil?`.
p = Proc.new { |ary| ary.map(&:nil?) }
# You can apply a Proc by using the method `call`, or by doing:
# p.([1, nil, 2])
# p[[1, nil, 2]]
p.call([1, nil, 2]) # => [false, true, false]