我在Ruby中有这个功能
def translate word
vowels=["a","e","I","O","U"]
i=1.to_i
sentense=word.split(" ").to_a
puts sentense if sentense.length >=1
sentense.split("")
puts sentense
end
Run Code Online (Sandbox Code Playgroud)
我有这个短语"这是一个测试短语",起初我想创建一个看起来像这样的数组:
["this","is","a", "test", "phrase"]
Run Code Online (Sandbox Code Playgroud)
然后我想创建另一个数组看起来像:
[["t","h","i","s"],["i","s"],["a"],["t","e","s","t"],["p","h","r","a","s","e"].
我试过了
sentense=word.split(" ").to_a
new_array=sentense.split("").to_a
Run Code Online (Sandbox Code Playgroud)
但它不起作用
你可以使用String#split,Enumerable#map和String#chars:
p "this is a test phrase".split.map(&:chars)
# => [["t", "h", "i", "s"], ["i", "s"], ["a"], ["t", "e", "s", "t"], ["p", "h", "r", "a", "s", "e"]]
Run Code Online (Sandbox Code Playgroud)
string.split(' ')可以写成string.split,所以你可以省略在括号中传递空格.
这也给你一个数组,没有必要使用to_a,你将有一个数组["this", "is", "a", "test", "phrase"],所以你可以使用map来获取一个新的数组,并使用.split('')或者为其字符数组中的每个元素.chars.