Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array.to_s return brackets?

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"]
like image 664
user1144553 Avatar asked Jan 12 '12 03:01

user1144553


People also ask

Which method is used to enumerate over an array returning an array matching the result of the executed block for each element in Ruby?

The map method iterates over an array applying a block to each element of the array and returns a new array with those results.


3 Answers

This print the array as is without brackets

array.join(", ")
like image 186
Erick Eduardo Garcia Avatar answered Nov 11 '22 02:11

Erick Eduardo Garcia


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\"]"
like image 40
josephrider Avatar answered Nov 11 '22 01:11

josephrider


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]
like image 24
ian Avatar answered Nov 11 '22 02:11

ian