Different way to declare class method to Ruby Class
2015/10/24
There are many ways to declare class method in ruby.
Most common way of declare class method is:
Using most common self
1
2
3
4
5
6
7
classFoodefself.capitalize_name"My captalize name is #{name.upcase}"endendprintMyClass.capitalize_name# => My captalize name is Foo
In this method we use class name instead of self:
1
2
3
4
5
6
7
8
# approach 2classFoodefFoo.capitalize_name"My captalize name is #{name.upcase}"endendprintMyClass.capitalize_name# => My captalize name is Foo
First declare class without method, then add method:
1
2
3
4
5
6
7
8
# approach 3classFoo;end# defining a class method out with the class definitiondefFoo.capitalize_namename.upcaseendprintMyClass.capitalize_name# => My captalize name is Foo
First declare class without method, then add method:
1
2
3
4
5
6
7
8
9
10
# approach 4# define a new class named MyClass# here we can see that our declare class just object of ClassFoo=Class.new# add the capitalize_name to MyClassdefFoo.capitalize_namename.upcaseendprintMyClass.capitalize_name# => My captalize name is Foo