BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Ruby - 2. Class and Instance Variables 2020

RubyOnRails_logo




Bookmark and Share





bogotobogo.com site search:




Class and Instance Variables
Sample class A

Here is a sample class that has setter and getter method:

#!/usr/bin/ruby
# class1.rb
# How to class

class Animal
   def initialize
      puts "Create an animal"
   end

   def set_name(new_name)
      @name = new_name
   end

   def get_name
      @name
   end

   def name
      @name
   end

   def name=(new_name)
      if new_name.is_a?(Numeric)
         puts "Number not allowed"
      else
         @name = new_name
      end
   end
end

# creating an animal object
cat = Animal.new

# set name
cat.set_name("Yaong")

# get name 1
puts cat.get_name

# get name 2
puts cat.name

# set name 2
cat.name = "Yaong2"
puts cat.name
puts cat.get_name

Output:

$ ./class1.rb
Create an animal
Yaong
Yaong
Yaong2
Yaong2




Sample class B

Here is another sample class that has setter and getter method with short cuts (more compact):

class Dog 
   # getter
   attr_reader :name, :height, :weight

   # setter
   attr_writer :name, :height, :weight
   ...

We can combine the getter/setter into one:

#!/usr/bin/ruby
# class2.rb
# How to class #2

class Dog
   # getter & setter
   attr_accessor :name, :height, :weight

   def bark
      return "Dog bark"
   end
end

# create a dog object
hunter = Dog.new

# set name
hunter.name = "Hunter"

puts hunter.name

Output:

$ ./class2.rb
Hunter




Inheritance

We want to make a new class that inherits from the Dog class we created in the previous section:

#!/usr/bin/ruby
# class3.rb
# How to class #3 with child class

class Dog
   # getter & setter
   attr_accessor :name, :height, :weight
 
   def bark
      return "Dog bark"
   end
end

# create a dog object
hunter = Dog.new

# set name
hunter.name = "Hunter"

puts hunter.name

class MongolDog < Dog
   def bark
      return "Mongol bark"
   end
end

mong = MongolDog.new
mong.name = "Mongoo"

printf "%s barks %s" \n", mong.name, mong.bark()

Output:

$ ./class3.rb
Hunter
Mongoo barks Mongol bark 




Polymorphism
#!/usr/bin/ruby
# bird.rb

class Bird
   def tweet(bird_type)
      bird_type.tweet
   end
end

class Duck < Bird
   def tweet
      puts "Quack quack"
   end
end

class Owl < Bird
   def tweet
      puts "Hoot"
   end
end

generic_bird = Bird.new
generic_bird.tweet(Duck.new)
generic_bird.tweet(Owl.new)

Output:

$ ./bird.rb
Quack quack
Hoot




Instance Variables

We can see the instance variables whenever we inspect the object, and there are other ways of accessing them.

So what methods do exist for Hello objects defined in the previous chapter?

irb(main):020:0> Hello.instance_methods
=> [:hi, :bye, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
irb(main):021:0> 

Too many methods?
If we want only the methods we defined, we do this:

irb(main):021:0> Hello.instance_methods(false)
=> [:hi, :bye]

Now, it's time to see which methods our Hello object responds to:

irb(main):041:0> g.respond_to?("name")
=> false
irb(main):042:0> g.respond_to?("say_hi")
=> true
irb(main):043:0> g.respond_to?("to_s")
=> true

We see the Hello object recognizes hi. THe to_s method converts something to a string, a method that's defined by default for every object. However, it doesn't know name.





Modifying the Hello class

Is there a way of changing the name?
Ruby provides an easy way of providing an access to an object's variables:

irb(main):004:0> class Hello
irb(main):005:1>   attr_accessor :name
irb(main):006:1> end
=> nil

Using attr_accessor defined two new methods for us, name to get the value, and name= to set it.

In Ruby, we can open a class up again and modify it. The changes will be present in any new objects we create and even available in existing objects of that class. So, let's create a new object and play with its @name property.

irb(main):022:0> h = Hello.new("Hansson")
=> #
irb(main):023:0> h.respond_to?("name")
=> true
irb(main):024:0> h.respond_to?("name=")
=> true
irb(main):025:0> h.hi
Hi Hansson!
=> nil
irb(main):026:0> h.name = "Matz"
=> "Matz"
irb(main):027:0> h
=> #
irb(main):028:0> h.name
=> "Matz"
irb(main):029:0> h.hi
Hi Matz!
=> nil




Running a Ruby file

Note that the Hello class can only deal with one person at a time.

We'll do two things here:

  1. Making a class that can handle a list of people.
  2. Create a Ruby file and run it rather than doing interactive works with irb.

Here is the file, hello.rb:

#!/usr/bin/env ruby

class Hello
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end

  # hi to everybody
  def hi
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("each")
      # @names is a list of some kind, iterate!
      @names.each do |name|
        puts "Hello #{name}!"
      end
    else
      puts "Hello #{@names}!"
    end
  end

  # bye to everybody
  def bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end
end

if __FILE__ == $0
  h = Hello.new
  h.hi
  h.bye

  # Change name to be "Hansson"
  h.names = "Hansson"
  h.hi
  h.bye

  # Change the name to an array of names
  h.names = ["Brahms", "Chopin", "Rachmaninov", "Tchaikovsky", "Satie"]
  h.hi
  h.bye

  # Change to nil
  h.names = nil
  h.hi
  h.bye
end

Run it:

$ ruby hello.rb
Hello World!
Goodbye World.  Come back soon!
Hello Hansson!
Goodbye Hansson.  Come back soon!
Hello Brahms!
Hello Chopin!
Hello Rachmaninov!
Hello Tchaikovsky!
Hello Satie!
Goodbye Brahms, Chopin, Rachmaninov, Tchaikovsky, Satie.  Come back soon!
...
...

Note that the hi() is now looking at the @names instance variable to make decisions. If it's nil, it just prints out three dots.





Loop

If the @names object responds to each, it is something that we can iterate over, so iterate over it. If not, just let it get turned into a string automatically and do the default.

In the following code:

@names.each do |name|if __FILE__ == $0
  h = Hello.new
  h.hi
  h.bye

  # Change name to be "Hansson"
  h.names = "Hansson"
  h.hi
  h.bye

  # Change the name to an array of names
  h.names = ["Brahms", "Chopin", "Rachmaninov", "Tchaikovsky", "Satie"]
  h.hi
  h.bye

  # Change to nil
  h.names = nil
  h.hi
  h.bye
end

  puts "Hello #{name}!"
end

each is a method that accepts a block of code then runs that block of code for every element in a list. The variable between pipe ('|') characters is the parameter for this block.





join() method

Let's look at the code for bye():

  # bye to everybody
  def bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end

The bye method doesn't use each, instead it checks to see if @names responds to the join method, and if so, uses it. Otherwise, it just prints out the variable as a string. This method of not caring about the actual type of a variable, just relying on what methods it supports is known as Duck Typing, as in "if it walks like a duck and quacks like a duck". The benefit of this is that it doesn't unnecessarily restrict the types of variables that are supported. If someone comes up with a new kind of list class, as long as it implements the join method with the same semantics as other lists, everything will work as planned.





if __FILE__ == $0

In the line:

if __FILE__ == $0

__FILE__ is a variable that contains the name of the current file. $0 is the name of the file used to start the program. This check says "If this is the main file being used". This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.

This is doing the same thing that if __name__ == '__main__': is doing in Python.



Ruby on Rails

  • Ruby On Rails Home
  • Ruby - Input/Output, Objects, Load
  • Ruby - Condition (if), Operators (comparison/logical) & case statement
  • Ruby - loop, while, until, for, each, (..)
  • Ruby - Functions
  • Ruby - Exceptions (raise/rescue)
  • Ruby - Strings (single quote vs double quote, multiline string - EOM, concatenation, substring, include, index, strip, justification, chop, chomp, split)
  • Ruby - Class and Instance Variables
  • Ruby - Class and Instance Variables II
  • Ruby - Modules
  • Ruby - Iterator : each
  • Ruby - Symbols (:)
  • Ruby - Hashes (aka associative arrays, maps, or dictionaries)
  • Ruby - Arrays
  • Ruby - Enumerables
  • Ruby - Filess
  • Ruby - code blocks and yield
  • Rails - Embedded Ruby (ERb) and Rails html
  • Rails - Partial template
  • Rails - HTML Helpers (link_to, imag_tag, and form_for)
  • Layouts and Rendering I - yield, content_for, content_for?
  • Layouts and Rendering II - asset tag helpers, stylesheet_link_tag, javascript_include_tag
  • Rails Project
  • Rails - Hello World
  • Rails - MVC and ActionController
  • Rails - Parameters (hash, array, JSON, routing, and strong parameter)
  • Filters and controller actions - before_action, skip_before_action
  • The simplest app - Rails default page on a Shared Host
  • Redmine Install on a Shared Host
  • Git and BitBucket
  • Deploying Rails 4 to Heroku
  • Scaffold: A quickest way of building a blog with posts and comments
  • Databases and migration
  • Active Record
  • Microblog 1
  • Microblog 2
  • Microblog 3 (Users resource)
  • Microblog 4 (Microposts resource I)
  • Microblog 5 (Microposts resource II)
  • Simple_app I - rails html pages
  • Simple_app II - TDD (Home/Help page)
  • Simple_app III - TDD (About page)
  • Simple_app IV - TDD (Dynamic Pages)
  • Simple_app V - TDD (Dynamic Pages - Embedded Ruby)
  • Simple_app VI - TDD (Dynamic Pages - Embedded Ruby, Layouts)
  • App : Facebook and Twitter Authentication using Omniauth oauth2
  • Authentication and sending confirmation email using Devise
  • Adding custom fields to Devise User model and Customization
  • Devise Customization 2. views/users
  • Rails Heroku Deploy - Authentication and sending confirmation email using Devise
  • Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger I
  • Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger II
  • OOPS! Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger (Trouble shooting)








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Ruby on Rails



Ruby On Rails Home

Ruby - Input/Output, Objects, Load

Ruby - Condition (if), Operators (comparison/logical) & case statement

Ruby - loop, while, until, for, each, (..)

Ruby - Functions

Ruby - Exceptions (raise/rescue)

Ruby - Strings (single quote vs double quote, multiline string - EOM, concatenation, substring, include, index, strip, justification, chop, chomp, split)

Ruby - Class and Instance Variables

Ruby - Class and Instance Variables II

Ruby - Modules

Ruby - Iterator : each

Ruby - Symbols (:)

Ruby - Hashes (aka associative arrays, maps, or dictionaries)

Ruby - Arrays

Ruby - Enumerables

Ruby - Filess

Ruby - code blocks and yield

Rails - Embedded Ruby (ERb) and Rails html

Rails - Partial template

Rails - HTML Helpers (link_to, imag_tag, and form_for)

Layouts and Rendering I - yield, content_for, content_for?

Layouts and Rendering II - asset tag helpers, stylesheet_link_tag, javascript_include_tag

Rails Project

Rails - Hello World

Rails - MVC and ActionController

Rails - Parameters (hash, array, JSON, routing, and strong parameter)

Filters and controller actions - before_action, skip_before_action

The simplest app - Rails default page on a Shared Host

Redmine Install on a Shared Host

Git and BitBucket

Deploying Rails 4 to Heroku

Scaffold: A quickest way of building a blog with posts and comments

Databases and migration

Active Record

Microblog 1

Microblog 2

Microblog 3 (Users resource)

Microblog 4 (Microposts resource I)

Microblog 5 (Microposts resource II)

Simple_app I - rails html pages

Simple_app II - TDD (Home/Help page)

Simple_app III - TDD (About page)

Simple_app IV - TDD (Dynamic Pages)

Simple_app V - TDD (Dynamic Pages - Embedded Ruby)

Simple_app VI - TDD (Dynamic Pages - Embedded Ruby, Layouts)

App : Facebook and Twitter Authentication using Omniauth oauth2

Authentication and sending confirmation email using Devise

Adding custom fields to Devise User model and Customization

Devise Customization 2. views/users

Rails Heroku Deploy - Authentication and sending confirmation email using Devise

Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger I

Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger II

OOPS! Deploying a Rails 4 app on CentOS 7 production server with Apache and Passenger (Trouble shooting)











Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master