Created
September 9, 2011 01:20
-
-
Save kinopyo/1205255 to your computer and use it in GitHub Desktop.
It shows how to enhance ruby class by define a new method to String class. This is just for study.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
def sex_code | |
if ["male", "男"].include? self | |
0 | |
elsif self == "女" | |
1 | |
else | |
self | |
end | |
end | |
end | |
p String.instance_methods.grep(/^sex/) # => [:sex_code] | |
p "male".sex_code # => 0 | |
p "女".sex_code # => 1 | |
p "other".sex_code # => "other" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.class_eval do | |
def sex_code | |
if ["male", "男"].include? self | |
0 | |
elsif self == "女" | |
1 | |
else | |
self | |
end | |
end | |
end | |
p String.instance_methods.grep(/^sex/) # => [:sex_code] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def String.hello | |
"hello from String class methods" | |
end | |
p String.singleton_methods.grep(/hello/) | |
p String.hello # => "hello from String class methods" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment