-2

When I use get.chomp and use an array ([1,2]) it outputs to a string ("[1,2]"). I want to change the string to an array so the method can work. How do I do this?

def sum(array) 
    array.inject(:+)
end

puts("Please enter an array.")
array = gets.chomp 

puts sum(array)
=>[1,2]
=>[1,2]
nphamily
  • 13
  • 3
  • The code works as expected and returns 3: http://ideone.com/KIsVbs – Jordan Running Sep 20 '15 at 04:42
  • 2
    Are you sure `sum(array)` doesn't raise an `ArgumentError` exception? The problem is that `array` is a string (`gets` returns a string). You need to pass an array to `sum`, The way to do that is `array = []; array << gets.to_i; array << gets.to_i`. Then it will work. – Cary Swoveland Sep 20 '15 at 04:55
  • this question is a duplicate .... http://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby – z atef Sep 20 '15 at 05:21
  • 1
    It is not a duplicate. (At least it's not a duplicate of the question @Null cites.) The question is why the method doesn't work. It doesn't work because a string, rather than an array, is passed as the argument. – Cary Swoveland Sep 20 '15 at 05:29
  • @CarySwoveland ... and arguably because the code does not check the type passed in. – David Aldridge Sep 20 '15 at 07:57
  • @David, yes. I wasn't thinking in my first comment. The exception would be that the value of `array` (a string) does not have a method `inject` (i.e., no instance method `String#inject`). – Cary Swoveland Sep 20 '15 at 08:02

3 Answers3

1

Your input converted into string, so you have to parse the array again before do any operation.

 def sum(array) 
    array = array[1..-2].split(',').collect! {|n| n.to_i} if array.is_a?(String)
    array.inject{|sum,e| sum + e }
 end

Output based on your input

> sum("[1,2]")
=> 3
Rokibul Hasan
  • 4,078
  • 2
  • 19
  • 30
  • input is not converted into string, it is a string :) – Andrey Deineko Sep 20 '15 at 10:39
  • the guys putting `[1,2]` this is not an `string` its an `array`, but the way he take input is `string`, I mean that. If you have problem with the language, its open for edit :) – Rokibul Hasan Sep 20 '15 at 10:49
  • `gets` returns tha input line as a string value, so no matter what you put there, it is a string. – Andrey Deineko Sep 20 '15 at 10:59
  • Arguing is about opinion. Ruby's built in methods are not subject for opinionated discussion, [they are what they are](http://ruby-doc.org/core-2.2.3/Kernel.html#method-i-gets) – Andrey Deineko Sep 20 '15 at 19:43
0

Using the concept that anything that is not an integer when converted to integer is 0.

2.3.1 :069 > sum = 0
=> 0
2.3.1 :070 > a.split("").each { |x| sum += x.to_i }
=> ["[", "1", ",", "2", "]"]
2.3.1 :071 > sum
=> 3

OR

2.3.1 :106 >   sum = 0
=> 0
2.3.1 :107 > a.split("").map {|x| sum += x.to_i }.max
=> 3
Siva Praveen
  • 2,213
  • 17
  • 20
-1

There's always the reduce(:+)

> [1,2,3].reduce(:+)
=> 6
Matthew
  • 2,035
  • 4
  • 25
  • 48