racingrails

Ruby_notes

Dec 21st, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.10 KB | None | 0 0
  1. Class names in Ruby always start with a capital letter.
  2.  
  3. some source code demonstrating a class
  4.  
  5. class Person
  6.   attr_accessor :name, :age, :gender
  7. end
  8.  
  9. attr stands for "attribute" and accessor roughly means "make these attributes accessible to be set and changed at will.
  10.  
  11. person_instance = Person.new
  12. person_instance.name = "Robert"
  13. person_instance.age = 52
  14. person_instance.gender = "male"
  15.  
  16. puts person_instance.name
  17.  
  18. inheritance
  19. class Pet
  20.  attr_accessor :name, :age, :gender, :color
  21. end
  22.  
  23. class Cat < Pet
  24. end
  25.  
  26. class Dog < Pet
  27.  def bark
  28.    puts "woof"
  29.  end
  30. end
  31.  
  32. class Snake < Pet
  33.  attr_accessor :length
  34. end
  35.  
  36. a_dog = Dog.new
  37. a_dog.bark
  38.  
  39. puts a_dog.class  #outputs Dog
  40. puts 2.class      #outputs Fixnum numbers are objects of the Fixnum class
  41. puts "This is a test".length  #outputs 14
  42.  
  43. puts "foobar".sub('bar', 'foo') #outputs foofoo
  44.  
  45. .sub only does one substitution at a time, on the first instance of the text to match, whereas gsub does
  46. multiple subsitutions at once.
  47. puts "this is a test".gsub('i','') #outputs ths s a test
  48.  
  49. #force integers to float
  50. 9.to_f / 5
  51. #or
  52. 9.0 / 5
Advertisement
Add Comment
Please, Sign In to add comment