-1

I wrote a method that takes an array of numbers, adds the number 2 to it, and then returns an array of strings.

def add_two(array)
  new_array = array.map{|x| "#{x} + 2 =  #{x + 2}"}
  new_array.to_s
end

The following is a test result:

enter image description here

I have an unwanted \ in my return. I am trying to figure out where the \ is coming from. Can someone point me in the right direction?

sawa
  • 165,429
  • 45
  • 277
  • 381
jonjon
  • 121
  • 2
  • 10

2 Answers2

5

It is coming from to_s that you have at the end. You are converting an array of strings (which is presumably already what you want) into a single string that contains double quotations (which must be escaped by \). To fix it, just remove your line with to_s.

sawa
  • 165,429
  • 45
  • 277
  • 381
1

Its not adding extra \s. \ is escape character to escape " which is part of the result String. Here:

a = add_two(array)
# => "[\"1 + 2 =  3\", \"2 + 2 =  4\", \"3 + 2 =  5\"]"

puts a
# ["1 + 2 =  3", "2 + 2 =  4", "3 + 2 =  5"]

or directly:

puts add_two(array)
# ["1 + 2 =  3", "2 + 2 =  4", "3 + 2 =  5"]
shivam
  • 16,048
  • 3
  • 56
  • 71
  • Thanks. But when I "puts add_two(array)", I just get nil in my return – jonjon Jul 01 '15 at 09:19
  • yes. because `puts` prints the output and returns `nil`. I did that just to explain you what's happening. In short, you need not to worry about \ in your result. Your actual code works fine and \ does not even exist. – shivam Jul 01 '15 at 09:23
  • I see no back slash on my output, i tried exactely what you wrote and it gave me what you are searching for. – Mourad Jul 01 '15 at 09:33