Page 1 of 1
ruby operation on arrays with nils
Posted: Tue Jan 19, 2016 9:53 pm
by tester
Scenario. Two input arrays, that on gui level contain empty lines. Nil lines are not zero's in this case. How to perform math operations on two such arrays in a way, that nil input (in one or other aray) produces nil output?
Example:
array1 + array2 = array3
1 + 5 = 6
nil + 6 = nil
2 + nil = nil
0 + 8 = 8
3 + 9 = 12
I'm guessing it would have to accept string array inputs and string array output.
Re: ruby operation on arrays with nils
Posted: Tue Jan 19, 2016 11:34 pm
by tulamide
Code: Select all
a = 1, nil, 2, 0, 3
b = 5, 6, nil, 8, 9
c = a.zip(b).map {|x, y| if x == nil or y == nil then nil else x+y end}
# c is [6, nil, nil, 8, 12]
Re: ruby operation on arrays with nils
Posted: Wed Jan 20, 2016 10:12 am
by tester
Not exactly working.
If inputs are set to string arrays, then values are connected, like 1+5=15. If inputs are float arrays, then nil is converted to 0 before it comes to ruby. Plus - the if statement seems to be ignored anyway. So input string values must be converted within ruby window to floats (but with nils different from 0's), before processing via math.
Re: ruby operation on arrays with nils
Posted: Wed Jan 20, 2016 1:18 pm
by tulamide
It wasn't clear from your description, that the arrays would be green ones. A good example of why a schematic can yield better help results

For feeding green arrays into Ruby in the way you need them, only strings make sense. You'd then have to change the algorithm to
Code: Select all
@a.zip(@b).map {|x, y| if x == "" or y == "" then "" else x.to_f+y.to_f end}
See also attached fsm.
Re: ruby operation on arrays with nils
Posted: Wed Jan 20, 2016 5:45 pm
by tester
Thanks, this one works.
Not on all machines I have the FS installed.