坚持分裂弦乐

问题描述 投票:0回答:2

我的目标是在空格' '上分割下面的字符串,以获得字符串中的单词集合。

'Fear is the path to the dark side'String#split(',')

我无法弄清楚使用什么方法。我尝试了如上所述,还有.split ('')和其他一些人。有帮助吗?

ruby
2个回答
4
投票

您错误地解释了该文档。当文档描述实例方法时,您需要一种方法来描述某个类中的对象,因为该方法适用于该类的任何实例。通常的做法是编写类名来表示该类的任意实例。完成此操作后,#字符用于表示.,以便将其与实际要将方法应用于String而不是它的实例区分开来。表达方式:

String#split(',')

在文档意味着用String的任何实例替换String,并写.而不是#像:

'Fear is the path to the dark side'.split(',')

然后,你必须选择合适的参数,在这种情况下是" "


1
投票

只要使用String#split

如果省略pattern,则使用$;的值。如果$;nil(这是默认值),则str在空格上分割,就好像指定了' '一样。

'Fear is the path to the dark side'.split
# => ["Fear", "is", "the", "path", "to", "the", "dark", "side"]
© www.soinside.com 2019 - 2024. All rights reserved.