Adding a string in Ruby

Asked

Viewed 77 times

1

all right? I’m learning Ruby So I have a Ruby Fundamentals exercise that asks for the following: I have to add the items of a string, the problem is that this string is like this:

7
-3
10
0
-5

I tried to use reduce and even inject so that they add up, the problem is that I have no idea how to get them lined up, tried with chomp and was not, not yet tried with gsub.

class Numbers
  def sum_text(numbers_text)
   numbers_text.map(&:to_f).reduce(:+)
  end
end
  • From Ruby 2.4.6 you can replace this .reduce(&:+) for .sum

1 answer

3


I believe the trick is to give one String.split in the string separating by the line break character \n (if it is Windows and came from a file might be coming "\r\n"). You must return a list (in Ruby you call the array right?) with each item being a line without the \n, then you process this array.

lines = numbers_text.split("\n")

Then you do: https://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby depending on your version (you may have to first apply a string to integer conversion).

  • THANK YOU!!! It worked first!!!

  • @Isabellasantiago For nothing. But do the [tour] to know how to thank you better when the question answered you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.