Why does Array.to_s return brackets?

可紊 提交于 2019-12-12 07:47:29

问题


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

回答1:


This print the array as is without brackets

array.join(", ")



回答2:


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:

page_array.join

If there are multiple elements to the array:

page_array.join(" ")

This will make:

page_array = ["test","this","function"]

return:

"test this function"

What "to_s" on an Array returns, depends on the version of Ruby you are using as mentioned above. 1.9.X returns:

"[\"test\"]"



回答3:


You need to show us the regex to really fix this properly, but this will do it:

Replace this

partial_url = page_array[0].to_s

with this

partial_url = page_array[0][0]



回答4:


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.

page_array = page.scan(/regex/).flatten

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.



来源:https://stackoverflow.com/questions/8829600/why-does-array-to-s-return-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!