Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

ruby class

class Dog # Initialize class!
    def initialize(name) # Initialize function of class Dog
        @name = name # Set name to param in class
    end

    def print_name() # Function to print out the name in params
        puts @name # Puts!
    end
end

my_dog = Dog.new "Bruno" # Create class and save it in variable
my_dog.print_name # Call print_name function from class

# Output:
# Bruno
Comment

ruby class variable

class Customer
   @@no_of_customers = 0
end
Comment

Classes and objects in Ruby

class Person
	def initialize(name) # this is an empty class
    end
end

p1 = Person.new("Ben")

class Person
	def initialize(name)
    	@name = name #This is an instance variable
    end
end

p1 = Person.new("Ben")

#To recall the name
class Person
	def initialize(name)
    	@name = name
    end
    def name
    	@name
    end
end

#We can call the above
p2=Person.new("Brian")
puts p2.name

#Attribute writers

class Person
  def initialize(name)
	@name = name
  end
  def name
  	@name
  end
  def password=(password)
	@password = password
  end
end

p3=Person.new("Margret")
p3.password = "lovydovy"
p p3
Comment

Ruby Classes

class Library
  attr_accessor :title, :author

  def readBook()
    puts "Reading #{self.title} by #{self.author}"
  end
end

book1 = Library.new()
book1.title = "Shreds of tenderness"
book1.author = "Dr Mwaniki"

book1.readBook()
puts book1.title
Comment

PREVIOUS NEXT
Code Example
Ruby :: ruby rails delete all of a model in console 
Ruby :: ActionController::InvalidAuthenticityToken rails when submitting form 
Ruby :: rails always 2 decimal 
Ruby :: rspec gem tutorial 
Ruby :: how to destroy a generate in rails 
Ruby :: true sting to true in rails 
Ruby :: random number rails 
Ruby :: ruby on rails binding.pry 
Ruby :: ruby join hash to string 
Ruby :: ruby frozen_string_literal 
Ruby :: list objects of a class ruby 
Ruby :: resources rails 
Ruby :: ! in ruby 
Ruby :: ruby merge arrays unique 
Ruby :: ruby to_a 
Ruby :: run a specific delayed job from console 
Ruby :: ruby pdf to file 
Ruby :: rails select arbitrary n element from array 
Ruby :: last select in rails 
Ruby :: rspec log to console 
Ruby :: add key and value to the beginning of a hash ruby 
Ruby :: rails loop 
R :: r clear variables 
R :: How to Export a DataFrame to Excel File in R 
R :: r return index of rows that have NA in dataframe 
R :: rename variables in r 
R :: principal component analysis in r 
R :: delete all rows that contain a string in R 
R :: how to summarise data but keep columns R 
R :: for loop in R dictionary 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =