Greg Barozzi wrote:
Mmcolli00 Mom wrote:
Do you know how I can convert or replace any value that gets back a
'nil' to 0?
For instance, the myArrayVal[0] may or may not contain a number and I
want the code to default to 0 if a nil is returned. I have not found any
documentation on this.
If you want to check each value in an array, try:
myArrayVal.each_index do |i|
myArrayVal[i] = 0 if myArrayVal[i].nil?
end
The each_index method allows you to iterate through the array and access each element specifically.
A less wordy way of writing this would be:
myArrayVal.each_index do |i|
myArrayVal[i] ||= 0
end
But using ||= will also convert a value of FALSE to 0, and that may not be a valid operation in your app. Hope this helps and good luck.
Following the examples, if you want to create a new array, you can also do this:
irb(main):001:0> a=
irb(main):002:0> a[3]=5
irb(main):003:0> a[6]=12.4
irb(main):004:0> a[7]=22
irb(main):005:0> p a
[nil, nil, nil, 5, nil, nil, 12.4, 22]
irb(main):007:0> b = a.collect { |x| x.nil? ? 0:x }
irb(main):008:0> p b
[0, 0, 0, 5, 0, 0, 12.4, 22]
···
--
Kind Regards,
Rajinder Yadav
http://DevMentor.org
Do Good ~ Share Freely