1

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.

1
  • Why is it you don't know which elements aren't numbers? And, why are there numbers mixed with strings? There's some code-smell implied by the array's contents. Commented Oct 8, 2014 at 20:06

2 Answers 2

6

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Numeric would also cover Bignum, Rational, Complex, etc, so I'd definitely recommend is_a?(Numeric), not is_a?(Fixnum). You probably don't care about Rational and such, and may not care about Float, but you almost always want to cover Bignum in addition to Fixnum.
-1

Here is what I would do.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.