我试图编写一个名为count_lines的独立方法,它返回输入字符串中的行数。 如果我运行此测试代码,它应该产生显示的输出:
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# Output:
Number of lines: 4
我对Ruby很新,我试图弄清楚这个实际输出的伪代码是否存在。请帮帮我!!
答案 0 :(得分:0)
我认为count_lines
是一个计算数组中元素数量的方法,你可以使用ruby提供的几个方法来计算元素的数量,为此查找Array Documentation,而%W
是一个红宝石细节,可以让你创建一个字符串数组,例如:
arr = %W{a b c}
arr # => ["a", "b", "c"]
它几乎使用任何特殊字符作为分隔符,例如使用.
作为分隔符
arr = %W.a b c.
arr # => ["a", "b", "c"]
因此,在问题/
的代码段中使用了分隔符,因此s
将评估如下:
s = %W/This
is
a
test./
s # => ["This", "is", "a", "test."]
以上解释了为什么下面的工作原理
def count_lines(arr)
arr.size
end
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# >> Number of lines: 4