[Ruby] [Ruby] I want to make an array from a character string with the split method. The reverse is also true.

1 minute read

What kind of writing method will result in the expected value when the string is arrayed, the array is converted to a string, and so on?

So let’s organize it with useless patterns!

Make string an array

We will use the split method.

split English translation: divide In other words, it is a method that divides cohesive things (character strings etc.) into elements. (Array) The argument will be * an image that specifies the boundaries of the cropped part *

I tried arraying from various patterns. The array you want to make is ["foo", "bar", "baz"].

Which writing method is right?

# Arrayed # return value
"foo bar baz".split ["foo", "bar", "baz"] # ○
"foo bar baz".split('') ["f", "o", "o", "", "b", "a", "r", "", "b", "a", "z"]
"foo bar baz".split(',') ["foo bar baz"]

"foobarbaz".split ["foobarbaz"]
"foobarbaz".split('') ["f", "o", "o", "b", "a", "r", "b", "a", "z"]
"foobarbaz".split(',') ["foobarbaz"]
"fooxbarxbaz".split('x') ["foo", "bar", "baz"] # ○

"foo, bar, baz".split ["foo,", "bar,", "baz"]
"foo, bar, baz".split('') ["f", "o", "o", ",", "", "b", "a", "r", ",", " ", "b", "a", "z"]
"foo, bar, baz".split(',') ["foo", "bar", "baz"]

"foo,bar,baz".split ["foo,bar,baz"]
"foo,bar,baz".split('') ["f", "o", "o", ",", "b", "a", "r", ",", "b", "a", "z"]
"foo,bar,baz".split(',') ["foo", "bar", "baz"] # ○

%w[foo bar baz] ["foo", "bar", "baz"] # ○

From these, there are *4 ways to write the expected array.

I want to make a string from the # array

We will use the join method. It is an image that puts * the value to be inserted between elements in the argument *.

# Stringification #return value
["foo", "bar", "baz"].join "foobarbaz"
["foo", "bar", "baz"].join('') "foobarbaz"
["foo", "bar", "baz"].join(',') "foo, bar, baz"

Bonus range is arrayed

# Array of ranges # return value
(0..9).to_a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
('a'..'z').to_a ["a",..,"z"]
(1..5).map{ |i| i**2) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]