Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a ruby method from method() to ().method

Tags:

ruby

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
like image 950
zacty Avatar asked Feb 02 '18 14:02

zacty


People also ask

How do you return a method in Ruby?

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.

What does TO_S do in Ruby?

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.

How do you typecast in Ruby?

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 .


2 Answers

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
like image 72
Ursus Avatar answered Nov 04 '22 00:11

Ursus


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"
like image 30
Sergio Tulentsev Avatar answered Nov 03 '22 23:11

Sergio Tulentsev