James
James

Reputation: 61

to_s method is not displaying the right result

I have an array: [1, "2", 3.0, ["a", "b"], "dog"]

typing array.to_s in my command prompt gives me this:

[1, \"2\", 3.0, [\"a\", \"b\"], \"dog\"]

Which is wrong, and it is suppose to give me this:

123.0abdog

Would someone explain to me why I'm not getting the right result?

Upvotes: 0

Views: 73

Answers (3)

user2012677
user2012677

Reputation: 5735

You first need to get rid of the nested array bby using flatten. Then you can join it into a string.

[1, "2", 3.0, ["a", "b"], "dog"].flatten.join

Upvotes: 0

Glyoko
Glyoko

Reputation: 2090

What it's giving you is the correct result. .to_s only ever returns a string representation of the object you call it on. In this case, it returns what the array looks like when represented as a string. This doesn't just mean flattening and combining all the elements into a string and is not generally intended to mean such.

If you want to run some code to get that result, try:

[1, "2", 3.0, ["a", "b"], "dog"].flatten.join

Upvotes: 3

Ilya
Ilya

Reputation: 13477

You, probably, want to join array:

[1, "2", 3.0, ["a", "b"], "dog"].join
=> "123.0abdog"

to_s works differently, according to the docs, it creates a string representation of an array:

[ "a", "b", "c" ].to_s     #=> "[\"a\", \"b\", \"c\"]"

Upvotes: 3

Related Questions