我有一个字符串

"1, 2, 3, 4"

我想把它转换成一个数组:

[1,2,3,4]

How?


当前回答

"1,2,3,4".split(",")作为字符串

“1、2、3、4”.split(", ")。将{|s| s.to_i}映射为整数

其他回答

"12345".each_char.map(&:to_i)

each_char的作用基本与split(")相同:它将字符串拆分为包含其字符的数组。

嗯,我现在才意识到,在原来的问题中,字符串包含逗号,所以我的答案并没有真正的帮助;-(..

字符串整数,没有空格作为字符串

arr = "12345"

arr.split('')

output: ["1","2","3","4","5"]

对于字符串整数,空格为字符串

arr = "1 2 3 4 5"

arr.split(' ')

output: ["1","2","3","4","5"]

字符串整数没有空格为整数

arr = "12345"

arr.split('').map(&:to_i)

output: [1,2,3,4,5]

为字符串

arr = "abc"

arr.split('')

output: ["a","b","c"]

解释:

Arr ->字符串,你将执行任何操作。 Split() ->是一个方法,它分割输入并将其存储为数组。 "或''或',' ->是一个值,需要从给定的字符串中删除。

转换具有逗号等分隔符的字符串的最简单方法就是使用split方法

"1,2,3,4".split(',') # "1", "2", "3", "4"]

你可以在ruby文档中找到更多关于如何使用split方法的信息

Divides str into substrings based on a delimiter, returning an array of these substrings. If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored. If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well. If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified. If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

对于整数:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

或者对于ruby的后续版本(>= 1.9 -正如Alex指出的那样):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]

"1,2,3,4".split(",")作为字符串

“1、2、3、4”.split(", ")。将{|s| s.to_i}映射为整数