我有一个类似['12','34','35','231']的ruby数组。
['12','34','35','231']
我想将它转换为类似'12','34','35','231'的字符串。
'12','34','35','231'
我该怎么做呢?
> a = ['12','34','35','231'] > a.map { |i| "'" + i.to_s + "'" }.join(",") => "'12','34','35','231'"
array.inspect.inspect.gsub(/\[|\]/, "")可以做到这一点
array.inspect.inspect.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'].join(', ') # => 12, 34, 35, 231
编辑:
"'#{['12','34','35','231'].join("', '")}'" # => '12','34','35','231'
一些字符串插值,添加第一个和最后一个单引号:P
还有另一种变化
a = ['12','34','35','231'] a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
> puts "'"+['12','34','35','231']*"','"+"'" '12','34','35','231' > puts ['12','34','35','231'].inspect[1...-1].gsub('"',"'") '12', '34', '35', '231'
array.map{ |i| %Q('#{i}') }.join(',')
试试这个代码['12','34','35','231']*","
['12','34','35','231']*","
将给你“12 34 35231”
我希望这就是你的结果,让我知道
string_arr.map(&:inspect).join(',') # or other separator
我觉得这种方式很有可读性,也很幼稚:
add_quotes =- > x{"'#{x}'"} p ['12','34','35','231'].map(&add_quotes).join(',') => "'12','34','35','231'"
你可以使用一些函数式编程方法,转换数据:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
假设你的数组:
arr=["1","2","3","4"]
方法将数组转换为字符串:
Array_name.join(",")
例子:
arr.join(",")
结果:
"'1','2','3','4'"