1

i tred creating a method called "Sum_plus_one" that accepts an array argument containing integers. Themethod should return the sum of the integers in the array after adding one to each of them.

example: sum_plus_one([1,2,3])

result should be: 9

my code looks like this

def sum_plus_one(*nums)

     for num in nums
     num + 1
     end
     total = 0
     for num in nums
     total += num
     end
 return total
end
2
  • 1
    num + 1 has no effect on the contents of the array. Commented Feb 24, 2014 at 1:07
  • thanks for the reply i'm still a newbie in Ruby Commented Feb 24, 2014 at 1:09

5 Answers 5

5

Why not do a little bit of math beforehand and see that summing the array-elements-plus-one is the same as summing the elements and then adding the array length? For example:

(5+1) + (6+1) + (11+1) = 5 + 6 + 11 + (1 + 1 + 1)
                       = 5 + 6 + 11 + 3

That gives you something nice and simple:

array.inject(:+) + array.length
Sign up to request clarification or add additional context in comments.

Comments

1

map/reduce is handy here:

def sum_plus_one(nums)
  nums.map(&:succ).reduce(:+)
end

Edit:

here is one way to make your code work:

def sum_plus_one(nums)
  nums.map! do |num|
    num + 1
  end

  total = 0
  for num in nums
    total += num
  end

  return total
end

2 Comments

wow it really help me thanks a lot, but what does the map function do?
map is an iterator. It changes each element in the array according to the code in the block(do |num| num + 1 end). In this case it adds 1 to each element in the array. We tend to use iterators in Ruby. It relieves us from keeping track of i's and j's and makes for clean, succinct, flexible code. See the map/reduce example above for comparison.
1

Functional Style Version

[1, 2, 3].reduce(0) {|acc, n| acc + n + 1}

Comments

1

Use Enumerable#inject

[105] pry(main)> arr
=> [1, 2, 3]
[106] pry(main)> arr.inject(0) { |var, i| var + i + 1 }
=> 9

So the method would look like

def sum_plus_one(*nums)
  nums.inject(0) { |var, num| var + num + 1 }
end

1 Comment

it is sufficient to return var + num + 1 without assigning it to var.
0

your problem is that you need to assign your num + 1 value to the corresponding element of the array that you are enumerating in the first loop.

maybe something like this:

for i in (0...nums.count)
    nums[i] += 1
end

after that your program should work

(yes, you can use fancy libraries or constructs instead of the above loop)

please note that you can eliminate the top loop and just add num + 1 to your total in the second loop.

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.