Ruby中的字符串到数组(String to Array in Ruby)

7 IT屋

I need my string: "---\n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\n" to convert to an array in Ruby

This is what I want it to be:

["aaaadddhh ddddggg", "bbbdddddf ff ddd", "cccf"]
解决方案

That's YAML. Use YAML.load(str) to unmarshal it from a string into an object.

> require 'yaml'
 => true
> YAML.load "---\n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\n"
 => ["aaaadddhh ddddggg", "bbbdddddf ff ddd", "cccf"]

Be aware that there are security risks in unmarshalling arbitrary YAML, so be sure that the source you are passing into it is trusted.

我需要我的字符串:" --- \n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\ \n" 转换为Ruby中的 array



这就是我想要的



  [" aaaadddhh ddddggg"," bbbdddddf ff ddd"," cccf"] 

解决方案

那是 YAML 。使用 YAML.load(str)将其从字符串解组到对象中。



 >需要'yaml'
=>真实的
> YAML.load" --- \n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\n"
=> [" aaaadddhh ddddggg"," bbbdddddf ff ddd"," cccf"]


请注意,有在解组任意YAML时存在安全风险,因此请确保您传递给它的源是受信任的。


本文地址:IT屋 » Ruby中的字符串到数组