Don't like ads? PRO users don't see any ads ;-)

oo_1.rb

By: saasbook on May 1st, 2012  |  syntax: Ruby  |  size: 0.82 KB  |  hits: 1,462  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class Movie
  2.   def initialize(title, year)
  3.     @title = title
  4.     @year = year
  5.   end
  6.   def title
  7.     @title
  8.   end
  9.   def title=(new_title)
  10.     @title = new_title
  11.   end
  12.   def year ; @year ; end
  13.   def year=(new_year) ; @year = new_year ; end
  14.   # How to display movie info
  15.   @@include_year = false
  16.   def Movie.include_year=(new_value)
  17.     @@include_year = new_value
  18.   end
  19.   def full_title
  20.     if @@include_year
  21.       "#{self.title} (#{self.year})"
  22.     else
  23.       self.title
  24.     end
  25.   end
  26. end
  27.  
  28. # Example use of the Movie class
  29.  
  30. beautiful = Movie.new('Life is Beautiful', '1997')
  31.  
  32. # What's the movie's name?
  33. puts "I'm seeing #{beautiful.full_title}"
  34.  
  35. # And with the year
  36. Movie.include_year = true
  37. puts "I'm seeing #{beautiful.full_title}"
  38.  
  39. # Change the title
  40. beautiful.title = 'La vita e bella'
  41. puts "Ecco, ora si chiama '#{beautiful.title}!'"