Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created September 9, 2011 01:20
Show Gist options
  • Save kinopyo/1205255 to your computer and use it in GitHub Desktop.
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.
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"
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]
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