I'm very new to programming so I'm sorry if I'm asking a really simple question. I've also already done my research and I still can't get what I want so I'm asking here.
So I'm writing a simple camelcase method - All words must have their first letter capitalized without spaces. Right now in order to call this function I have to type camelcase("hello there") which would return "Hello There" in interactive ruby. I am wondering how to convert this method into a different type of method(I think it's called a class method?) which would allow me to do this instead: "hello there".camelcase #=> "Hello There"
I've also seen that the syntax would be like so:
class String
def method()
...
end
end
But I really don't know how to apply it...
def camelcase(string)
newArray = []
newNewArray = []
array = string.split(" ")
for i in 0...array.length
newArray << array[i].capitalize
end
newNewArray = newArray.join(" ")
end
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
The to_s function in Ruby returns a string containing the place-value representation of int with radix base (between 2 and 36). If no base is provided in the parameter then it assumes the base to be 10 and returns.
Ruby has a well defined and often used typecasting infrastructure. to_s casts a value to a String , to_f casts a value to a Float , to_i casts a value to an Integer , etc. These are a helpful tool in our toolbox, but this too has limitations. First, there is no #to_* method that casts values into true or false .
In this way. I've used your_camelcase
because I'm not sure if that method does not exist in Ruby String class. Anyway, this is an instance method and you should use self
to refer to your string
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
You're almost there. Just put that method into String
class. Inside of that method, self
will refer to the string. You don't need to (and can't) pass it as a parameter.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With