Ruby/Class/Member method
Материал из Wiki.crossplatform.ru
Содержание |
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
a simple demonstration of a class with two methods
class Square def initialize(side_length) @side_length = side_length end def area @side_length * @side_length end end a = Square.new(10) b = Square.new(5) puts a.area puts b.area
Compare method
class MyNumber def initialize @secret = rand(20) end def hint puts "#{" not " if secret <= 10}greater than 10." end def secret @secret end end class OurNumber < MyNumber def hint lower = secret-rand(10)-1 upper = secret+rand(10)+1 "The number is somewhere between #{lower} and #{upper}." end end class OurNumber def compare(other) if secret == other.secret comparison = "equal to" else comparison = secret > other.secret ? "greater than" : "less than" end "This secret number is #{comparison} the secret number you passed in." end end a = OurNumber.new b = OurNumber.new puts a.hint puts b.hint a.rupare(b)
Define a method to retrieve the value.
class Horse def name @name = "Easy Jet" end end h = Horse.new h.name # The method name is the kind of method that is referred to as an accessor method or getter. # It gets a property (the value of a variable) from an instance of a class.
Defining Methods within a Class
class Account attr_reader :name, :balance def initialize(n, b) @name = n @balance = b end def add_interest(rate) @balance += @balance * rate / 100 end def display printf("%s, you have $%5.2f in your account.\n", @name, @balance) end end my_account = Account.new("Barry", 10.00) my_account.add_interest(5.0) my_account.display your_account = Account.new("Harriet", 100.00) your_account.add_interest(7.0) your_account.display
implement an each method, and get these methods for "free":
class AllVowels @@vowels = %w{a e i o u} def each @@vowels.each { |v| yield v } end end x = AllVowels.new x.each { |v| puts v }