I have the following string
78,87,test,test1,125
How can i convert this into an array
I need something like this
[78, 87, "test", "test1", 125]
How do i achieve it.
I have the following string
78,87,test,test1,125
How can i convert this into an array
I need something like this
[78, 87, "test", "test1", 125]
How do i achieve it.
尽管@struthersneil's answer回答了大部分问题,但添加此答案只是为了完整性。
"78,87,test,test1,125".split(',').map { |x| x=~ /^\d+$/ ? x.to_i : x }
> [78, 87, "test", "test1", 125]
注意数字的使用map
和regex
检查。您应该能够根据需要更改正则表达式和适当的助手,例如to_i
等to_f
。
如果您熟悉常用的类,如 String:http ://ruby-doc.org/core-2.0.0/String.html,您将更轻松地使用 ruby 。
你在这里想要的是:
"something,something,something".split ','