简体   繁体   中英

Iterating Over Array - Only Modifying Integers Ruby

I am trying to iterate over an array that contains both numbers and strings. Right now I am using the following code to accomplish this:

def mod_method(source_array, integer_increase)
source_array.map! do |x|
    if x.is_a? Fixnum
        x+=integer_increase
    else
        x
     end 
end
p source
end

So this will iterate over all the integers and add the second parameter (an integer) to all the values. What I don't understand is that is I do this instead:

def mod_method(source_array, integer_increase)
source_array.map! do |x|
    if x.is_a? Fixnum
        x+=integer_increase
     end 
end
p source
end

It will return everything that is not an integer as NIL. All I did was get rid of the 'else x'. Wouldn't it just skip over the elements that are not of type Fixnum? Why would it set those values to nil? I think if I can figure that out I will be able to refactor the code to make is look better. Thank you.

Because you're returning nil when it's not a number.

What you can do is call compact method after the iteration and it will get rid of nil values.

Like this:

def mod_method(source_array, integer_increase)
  source_array.map! do |x|
    if x.is_a? Fixnum
      x+=integer_increase
    end
  end.compact!
  p source
end

Here's how I'd do it:

def mod_method(ary, offset)
  ary.map{ |x| 
    (Fixnum === x) ? x += offset : x
  }
end

mod_method([1, 'a'], 1) # => [2, "a"]

That doesn't modify the passed-in array, it returns a new one. You already know to use map! if you want to mangle the array passed in.

Fixnum === x is a simple way of asking Fixnum if x is of its type:

Fixnum === 1 # => true
Fixnum === 'a' # => false

The rest of it is a ternary statement which is a single-line version of an if / then / else .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM