Reputation: 3
I'm trying to get map! to substitute out values if they're not in range but I can't get the range to work.
array[0].map! { |x| x != (2..8) ? "foo" : x}
I'm working with a 2d array that will have numbers and I need to replace anything not in range within the first array with another static value so it can be later sorted out.
The array I'm working on will look something like this
[ "bar", "2", "3", "baz"]
Which needs to be converted to look like
[ "foo", "2", "3", "foo" ]
Upvotes: 0
Views: 87
Reputation: 18762
For the given input array, you have strings as elements of your array. You need to convert the elements to numeric
before it can be compared with range. There are few methods that helps to check whether a number is part of a range or not: Range#cover?
, Range#include?
and Range#===
.
Here is one way to do this:
array[0].map! { |x| (2..8) === x.to_i ? x : "foo"}
Upvotes: 1
Reputation: 597
You can test the existence of an element in an Array like this:
(2..8).include? 1 => false
Upvotes: 1