[英]Ruby array to string conversion
I have a ruby array like ['12','34','35','231']
.我有一个像
['12','34','35','231']
这样的 ruby 数组。
I want to convert it to a string like '12','34','35','231'
.我想将它转换为像
'12','34','35','231'
这样的字符串。
How can I do that?我怎样才能做到这一点?
I'll join the fun with:我将加入乐趣:
['12','34','35','231'].join(', ')
EDIT:编辑:
"'#{['12','34','35','231'].join("', '")}'"
Some string interpolation to add the first and last single quote :P一些字符串插值来添加第一个和最后一个单引号:P
> a = ['12','34','35','231']
> a.map { |i| "'" + i.to_s + "'" }.join(",")
=> "'12','34','35','231'"
try this code ['12','34','35','231']*","
试试这个代码
['12','34','35','231']*","
will give you result "12,34,35,231"会给你结果“12,34,35,231”
I hope this is the result you, let me know我希望这是你的结果,让我知道
array.map{ |i| %Q('#{i}') }.join(',')
string_arr.map(&:inspect).join(',') # or other separator
I find this way readable and rubyish:我发现这种方式可读和红宝石:
add_quotes =- > x{"'#{x}'"}
p ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"
> puts "'"+['12','34','35','231']*"','"+"'"
'12','34','35','231'
> puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'")
'12', '34', '35', '231'
And yet another variation还有另一种变体
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
irb(main)> varA
=> {0=>["12", "34", "35", "231"]}
irb(main)> varA = Hash[*ex.collect{|a,b| [a,b.join(",")]}.flatten]
...
irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil
您可以使用一些函数式编程方法来转换数据:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
suppose your array :假设你的数组:
arr=["1","2","3","4"]
Method to convert array to string:数组转字符串的方法:
Array_name.join(",")
Example:例子:
arr.join(",")
Result:结果:
"'1','2','3','4'"
array.inspect.inspect.gsub(/\\[|\\]/, "")
可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.