我对编程非常陌生,所以如果我问了一个非常简单的问题,我很抱歉。我也已经做了我的研究,但我仍然不能得到我想要的,所以我在这里问。
因此,我正在编写一个简单的camelcase方法-所有单词的第一个字母都必须大写,不能有空格。现在,为了调用这个函数,我必须输入camelcase("hello there"),这将在交互式ruby中返回"Hello There“。我想知道如何将这个方法转换为不同类型的方法(我想它被称为类方法?)这样我就可以这样做了:"hello there".camelcase #=> "Hello“
我还看到语法是这样的:
class String
def method()
...
end
end但我真的不知道该怎么运用它..。
def camelcase(string)
newArray = []
newNewArray = []
array = string.split(" ")
for i in 0...array.length
newArray << array[i].capitalize
end
newNewArray = newArray.join(" ")
end发布于 2018-02-02 22:58:08
你就快到了。只需将该方法放入String类中即可。在该方法内部,self将引用该字符串。您不需要(也不能)将其作为参数传递。
class String
def camelcase
newArray = []
newNewArray = []
array = self.split(" ")
for i in 0...array.length
newArray << array[i].capitalize
end
newNewArray = newArray.join(" ")
end
end
'hello there'.camelcase # => "Hello There"发布于 2018-02-02 22:58:25
以这种方式。我之所以使用your_camelcase,是因为我不确定Ruby String类中是否不存在该方法。无论如何,这是一个实例方法,您应该使用self来引用您的字符串
class String
def your_camelcase
newArray = []
newNewArray = []
array = self.split(" ")
for i in 0...array.length
newArray << array[i].capitalize
end
newArray.join(" ")
end
end发布于 2018-02-03 00:22:42
您需要的输出不是Camel Case。Camelcase的例子是camelCase或CamelCase (没有空格)。
如果你只想把每个单词都大写,那就叫Title Case。titlecase的一个简单实现如下所示:
class String
def titlecase
self.split.map(&:capitalize).join(" ")
end
end
"hello world".titlecase #=> "Hello World"注意:要使其成为真正的camelcase实现,您需要用join替换join(" ")。
https://stackoverflow.com/questions/48585253
复制相似问题