Fuaad
Fuaad

Reputation: 440

Array and string in ruby

Hi amazing stackers!

date = "10/02/2021"
d1 = date.split("/")
d2 = d1.to_s
puts d1
puts d1.class
puts d2
puts d2.class

in the above code, d2 shows the data type "string" but it is displayed like an array. And d1 is an array but it doesn't have an array like form. Can you please resolve the confusion?

Upvotes: 0

Views: 142

Answers (2)

nPn
nPn

Reputation: 16748

Please see the documentation for the full details but

Array#to_s creates a string representation of the array by calling inspect on each element. Basically this creates a string that looks the way you would expect an array to look if you inspected it, ie p d2.

IO#puts when called with an array as the argument writes each element on a new line.

Upvotes: 0

Rajagopalan
Rajagopalan

Reputation: 6064

This is what you are expecting

date = "10/02/2021"
d1 = date.split("/")
d2 = d1.join
p "--------------------------"
p d1
p d1.class
p d2
p d2.class
p "--------------------------"

Output

"--------------------------"
["10", "02", "2021"]
Array
"10022021"
String
"--------------------------"

Use p instead puts, it will print the data along with it's structure. Use join to combine the array element into a string.

Upvotes: 1

Related Questions