Php 如何在ruby中将数组写入文件
我有如下数组Php 如何在ruby中将数组写入文件,php,ruby,arrays,file-io,Php,Ruby,Arrays,File Io,我有如下数组 Array ( [0] => abuse@peterstar.net [2] => hostmaster@peterstar.net [3] => noc@peterstar.net ) 我需要把它转换成下面的格式 :abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net 我知道这在php中很简单,如下所示 file_put_contents($file, ":".implode(",",
Array ( [0] => abuse@peterstar.net [2] => hostmaster@peterstar.net [3] => noc@peterstar.net )
我需要把它转换成下面的格式
:abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net
我知道这在php中很简单,如下所示
file_put_contents($file, ":".implode(",", $emails)."\n", FILE_APPEND | LOCK_EX);
但我如何在ruby中做到这一点
提前感谢。检查课程
File.open(yourfile, 'w') { |file| file.write(":#{your_array.join(',')}") }
如果要将文本附加到文件中,则需要以“附加”模式打开文件
我建议以更常见的格式(如YAML)存储数据
array = ['foo', 'bar', 'baz']
# write file
File.open('filename.yml', 'w') { |f| YAML.dump(array, f) }
# read file
array = File.open('filename.yaml') { |f| YAML::load(f) }
如果问题是如何转换字符串:
str = "Array ( {[0] => abuse@peterstar.net}, {[2] => hostmaster@peterstar.net},\
{[3] => noc@peterstar.net} )"
到字符串:
":abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net"
需要一个正则表达式:
':' + str.scan(/(?:=> )([^}]*)/).join(',')
显然需要:
和.join(',')
。让我们看看生成
str.scan(/.*?(?:=> )([^}]*)/)
# => [["abuse@peterstar.net"], ["hostmaster@peterstar.net"], ["noc@peterstar.net"]]
我不是regex专家,因此欢迎任何更正或改进建议
是一个“非捕获”组(因为(?:=>)
),它查找?:
“=>”
是一个捕获组,它接受所有字符,直到遇到([^}]*)
李>“}”
- 与
相当的ruby是内爆
。字符串上的加入
操作符的ruby等价物是
。ruby相当于写入文件:+
File.open(yourfile, 'w') do |file| file.write ':' + yourarray.join(',') + "\n" end
这和PHP有什么关系?那不是数组。修复后,请检查它是否有效(例如,在IRB中),然后编辑。如果您愿意,只需将其写成
,其中每个[ob0,ob1,…,obN]
都是一个Ruby对象。注意URL是字符串,所以必须用引号括起来。@Ultimater我知道php,正在尝试将php脚本修改为ruby。@上面的CarySwoveland是php的输出,而不是ruby中的ruby[abuse@peterstar.net, hostmaster@peterstar.net, noc@peterstar.net]你是说obi
是字符串吗?如果是这样,只需将其括在单引号或双引号中,删除对数组的引用,所有内容都应该清楚。但我需要如下输出:abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net :abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net :abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.net :abuse@peterstar.net,hostmaster@peterstar.net,noc@peterstar.netuser3155632,你需要通过编辑来澄清你的问题,而不是试图在评论中详细阐述。现在就做,否则你的问题几乎肯定会被版主扼杀。现在可能已经太晚了。@user3155632你是说追加模式吗?谢谢@xdazz它成功了这就是我所缺少的:)使用数组([0]=>abuse@peterstar.net [2] => hostmaster@peterstar.net [3] => noc@peterstar.net)
和File.write('filename.yaml',array.to_yaml)
yaml.load_filel('filename.yaml')
File.open(yourfile, 'w') do |file| file.write ':' + yourarray.join(',') + "\n" end