Hello,

For someone that already familiar with

1
Ruby
,
1
Ruby
can convert / manipulate string. But what
1
Ruby
can do?

Suppose we have string “hello world”. Can we manipulate it so it will be all uppercase? Yes, you can. Simply do

1
"hello world".upcase
it will return all character uppercase “HELLO WORLD”. Or if you want “Hello World” to become “hello world”, you can do
1
"Hello World".downcase
. You can also make it capitalize by doing
1
"hello world".capitalize
.

But doing

1
"hello world".capitalize
will give you “Hello world” because its only capitalize first character. What if you want to return “Hello World” instead of “Hello world”?

This is simple idea how to get return value “Hello World”.

  1. First, you split it with space
  2. Make it all capitalize
  3. And then join it again with space

This will give us “Hello World”.

You have to make

1
Ruby
understand what do you want. This is what you’ve to told to
1
Ruby
.
1
"hello world".split(" ").map(&:capitalize).join(" ")
. Simple, isn’t it?

Are you tired for repeating that code over and over? Please DRY , Dont Repeat Yourself! You can do awesome things like this :

class String
  def capitalize_all
    self.split(" ").map(&:capitalize).join(" ")
  end
end

But what on earth is that ??

It is not secret anymore that you can dinamically adding method to a class in

1
Ruby
. What we’ve done is we add new method called
1
capitalize_all
into
1
Ruby
1
String
class. Then once it settled we only need to call that method. For example :
1
"hello world".capitalize_all
.


OK you got me! i tricked you. hahaha :D

Actually you can just do

1
"hello world".titleize
to get
1
"Hello World"
. But i hope my post will give you and idea to create dynamic method.