简体   繁体   English

to_s方法返回不需要的“ \\”

[英]to_s method returning an unwanted “\”

I wrote a method that takes an array of numbers, adds the number 2 to it, and then returns an array of strings. 我编写了一个方法,该方法接受一个数字数组,向其添加数字2,然后返回一个字符串数组。

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

The following is a test result: 以下是测试结果:

在此处输入图片说明

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? 有人可以指出我正确的方向吗?

It is coming from to_s that you have at the end. 它来自最后的to_s 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 . 要解决此问题,只需使用to_s删除行。

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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM