GVictaChua
GVictaChua

Reputation: 21

Creating a method to modify elements in an array in Ruby with 2 arguments, one of them being the original array

I would like to create a method, mod_method(array, n) , where array is an array and n is a number. mod_method should take number n and add it to all internal numbers in array and return that new array.

For example, using array = ["I", "have", 3, "to", 4, "hours"], how would I find mod_method(array, 1) such that

mod_method(array,1)
 => ["I", "have", 4, "to", 5, "hours"]

I'm a noob and was only able to do this using the already defined array and number (let's use 1), as such:

array = ["I", "have", 3, "to", 4, "hours"]
=>[[0] "I",
  [1] "have",
  [2] 3,
  [3] "to",
  [4] 4,
  [5] "hours"]

numbers = array.values_at(2, 4)
=> [
  [0] 3,
  [1] 4

mod = numbers.map{|x| x + 1}
=> [
  [0] 4,
  [1] 5]
new_array = ["I", "have", mod[0], "to", mod[1], "hours"]
=> ["I", "have", 4, "to", 5, "hours"]

I have no idea how to do it with undefined arguments for the mod_method.

Upvotes: 1

Views: 66

Answers (2)

Johnson
Johnson

Reputation: 1749

Here is what I would do.

def mod_method(array,n)
  array.map do |e|
    e.is_a?(Integer) ? e + n : e
  end
end

Upvotes: -1

Arup Rakshit
Arup Rakshit

Reputation: 118261

Write the method as

def mod_method(array, n)
  array.map { |i| i.is_a?(Fixnum) ? (i + n) : i }
end

array = ["I", "have", 3, "to", 4, "hours"]
mod_method(array, 1) # => ["I", "have", 4, "to", 5, "hours"]

If your array contains both Fixnum and Float instances, and you want to add 1 with either of those instances. Then use the below method :-

def mod_method(array, n)
  array.map { |i| i.kind_of?(Numeric) ? (i + n) : i }
end

array = ["I", "have", 3.2, "to", 4, "hours"]
mod_method(array, 1) # => ["I", "have", 4.2, "to", 5, "hours"]

Upvotes: 6

Related Questions