Add method to a variable only : Member method « Class « Ruby






Add method to a variable only


company_name = 'Software'
def company_name.legalese
  return "#{self} is a registered trademark."
end

company_name.legalese
# => "Homegrown Software is a registered trademark of ConglomCo International."
'Some Other Company'.legalese
# NoMethodError: undefined method 'legalese' for "Some Other Company":String

 








Related examples in the same category

1.Define a method to retrieve the value.
2.a simple demonstration of a class with two methods
3.implement an each method, and get these methods for "free":
4.Compare method
5.Defining Methods within a Class