为什么 Array.to_s 返回括号?
对于数组,当我键入:
puts array[0]
==> text
然而当我键入时
puts array[0].to_s
==> ["text"]
为什么要使用括号和引号?我缺少什么?
附录:我的代码看起来像这样
page = open(url) {|f| f.read }
page_array = page.scan(/regex/) #pulls partial urls into an array
partial_url = page_array[0].to_s
full_url = base_url + partial_url #adds each partial url to a consistent base_url
puts full_url
:
http://www.stackoverflow/["questions"]
For an array, when I type:
puts array[0]
==> text
Yet when I type
puts array[0].to_s
==> ["text"]
Why the brackets and quotes? What am I missing?
ADDENDUM: my code looks like this
page = open(url) {|f| f.read }
page_array = page.scan(/regex/) #pulls partial urls into an array
partial_url = page_array[0].to_s
full_url = base_url + partial_url #adds each partial url to a consistent base_url
puts full_url
what I'm getting looks like:
http://www.stackoverflow/["questions"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将按原样打印数组,不带括号
This print the array as is without brackets
to_s 只是检查 Array 类的别名。
这并不是说这意味着很多,除了期望 array.to_s 返回一个字符串之外,它实际上返回 array.inspect ,根据方法的名称,这并不是您真正想要的。
如果您只想要“胆量”,请尝试:
如果数组中有多个元素:
这将使得:
返回:
数组上的“to_s”返回什么,取决于您使用的 Ruby 版本,如上所述。 1.9.X 返回:
to_s is just an alias to inspect for the Array class.
Not that this means a lot other than instead of expecting array.to_s to return a string it's actually returning array.inspect which, based on the name of the method, isn't really what you are looking for.
If you want just the "guts" try:
If there are multiple elements to the array:
This will make:
return:
What "to_s" on an Array returns, depends on the version of Ruby you are using as mentioned above. 1.9.X returns:
您需要向我们展示正则表达式才能真正正确修复此问题,但这可以做到:
将其替换
为此
You need to show us the regex to really fix this properly, but this will do it:
Replace this
with this
这不一定能解决为什么您得到双倍数组的问题,但您可以将其展平,然后像这样调用第一个元素。
扁平化会取出堆叠数组并创建一个级别,因此如果您有
[1,2,[3,[4,5,6]]]
并对其调用 flatten,您将得到[1,2,3,4,5,6]
它也比
array[0][0]
更健壮,因为,如果嵌套了两个以上的数组第一个元素,你会遇到同样的问题。不过,伊恩是正确的,如果没有看到正则表达式,我们无法找出根本原因。
This doesn't necessarily fix why you are getting a doubled-up array, but you can flatten it and then call the first element like this.
Flattening takes out stacked arrays and creates one level, so if you had
[1,2,[3,[4,5,6]]]
and called flatten on it, you would get[1,2,3,4,5,6]
It is also more robust than doing
array[0][0]
, because, if you had more than two arrays nested in the first element, you would run into the same issue.Iain is correct though, without seeing the regex, we can't suss out the root cause.