<
Ruby
>
上一篇

Machine Learning

没有下一篇咯

Ruby - Your First Choice for System Management(2019.12.11)

Environment: Mac OS and Unix system

Ruby version: ruby 2.6.3p62

1. Introduction to Ruby

1.1 Why Ruby?

1.2 Installation Ruby

1.Firstly, you should install the Homebrew which is the very brilliant package management software in Mac OS

$ sudo mkdir /usr/local/homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew

2.Next, use the brew command to install the Ruby automatically.

$ brew install ruby

1.3 Basic Knowledgement about the Terminal and Executable Environment

Ruby Files
Access the Ruby files with privileges of root

1.First you can create the empty Ruby file.

$ torch demo.rb

2.Give the executable permission to the file just created by yourself.

$ chmod u+x demo.rb
#OR you can use: chmod 777 demo.rb

3.Run the Ruby file

$ ./demo.rb
Some Tools before Coding

Ruby Grammar Retrieval Tool - ri

ri which has been included in the Ruby official package and installed in your system. It can provide the detailed information and help of kernel library amd standard library.
The usage of this tool is very simple:

$ ri <command and library you want to look up>
# For example 
$ ri puts
$ ri <class name>::<method>

For exiting this help interface, type ctr+D

Ruby shell - irb

irb is the command line like the python console activated by python which can accept the code in Ruby.

$ ls 
demo.rb
$ irb
irb(main):001:0> load './demo.rb'
=>true
irb(main):002:0> ....

You can exiting the command line by ctr+D

1.4 Mark Interpreter program to run Ruby file

If you have experience on coding the shell, you may feel familiar to indicate the interpreter program to run the ruby files. It’s not because of which program can run it, but to set up what kind of pattern in interpreter.
For example: #!/usr/bin/env ruby -w
This line set the interpreter in warning pattern which can show all the warning details.
For nomal use: #!/usr/bin/env

2. Meet Ruby

2.1 Variables in Ruby

Instance variable - We use the symbol @ to represent the variables apart from the class variables.

Number

String

Class Variable - We use the symbol @@ to represent the class variables .

class Demo   # for the name of class and module must start with the capital letter
	def initialize(A)
		@temp_variable = A  # instance variable
	end
	
	def add(B)
		@temp_variable += B
	end
	
	def judge
		if @temp_variable < 0 then "nil" #outputs true
		else "false" #outputs false
  
	def show(result)
    return result
  end

object_class = Demo.new(5) #call the function of initialize(Inheritance method)
object_class.judge

Boolean variable - The ture value can be represented by nil from the library NilClass. The false valude can be represented by false from the library FlaseClass

Global Variables - The variables with a $ sign and can be accessed in the entire program

$value = 10
def show_value
  p "The value is #{$value}"
  # If you change the sign $ to @
  # p "The value is #{@value}"
  # The program doesn't report the error but the result maybe not expectant
  # ======> "The value is "
end
show_value # => "The value is 10"

2.2 Class and Method

Class - It seems that class is the collection of different methods and variables. And class also can be inherited by another class to complete the function.

Method - The main block to imply the detail of function.

class Demo
  # Automatically called when Initialization
  def initilize(a)
    p 'This method can be automatically processed'
  end
  # method has the return value
  def square(number)
    result = number * number
    return result
  end
 	# Now we create method to show label of this class
  def display_infor
    p 'This is the first class\'s function'
  end
  # Create private method
  private
  def pr_function(*args)
    p 'This is a private methods'
  end
end

# This class can inherit from the Demo class
class Scapegoat < Demo
  def display
    p 'This is the second class\'s function'
  end
end

class_object = Demo.new() #=> This method can be automatically processed
# class_object.pr_function 
#     => private method `pr_function' called for #<Demo:0x00007fda10101340> (NoMethodError)

sec_class_object = Scapegoat.new()
sec_class_object.display
class Show
  def class_method
    p 'This is a class method'
  end
  
  def self.class_method:
    p 'This is a instance method'
  end 
end

show_object = Show.new
Show.class_method #=> This is a instance method
show_object.class_method #=> This is a class method
# Open your shell
$ irb
>> a = 23
=> 23
>> a.class
=> Integer
>> b = a.to_s
=> "23"
>> b.class
=> String
>> b = b.to_i
=> 23
>> b.class
=> Integer
>> exit

2.3 Macro

In Ruby, it is very difficult to use the symbol = to finish the operation of valuation for kernel. In another words, the interpreter tends to call the valuation method to finish this step. Fortunately, the Ruby provides Macro from the class library.

attr_reader The method to read the value of variable
attr_writer The method to create the valuation of variable
attr_accessor The method to create more than two functions for one variable
# For understanding the function of Macro Let's see below codes
# For the first class, the function is to assign the value to the class and read it
class Original
  # create the local variable in class and read it
  def read_variable
    p @name  # p = puts 
  end
  # assign the valur to this local variable
  def write_variable(temp)
    @name = temp
  end
end

# The second class (Macro) is the class has the same function as the first class
# Using the macro(Getter and Setter)
class Macro
  attr_accessor: variable
  # If you want to add variables than two:
  # attr_accessor :variable_1, :variable_2,...
  def greeting
    # DO NOT USE the 
    p "Hello #{@variable}"
  end 
end 
macro_object = macro.new
macro_object.variable = "Ruby"
macro_object.greeting #=> Hello Ruby

2.4 Block

Block:
Ruby provides two ways for programmers to using the block.

# First 
3.times { |i| puts i}
# second
3.times do |i|
  puts i
end

Method upto:

3.upto(10) {|i| puts i}
# => 3,4,5,6,7,8,9,10

2.5 Condition

a = 23
if a > 0
  puts nil
elsif a < 0
  puts false
else
  puts "Zero"
end
puts "a is more than zero" if a > 0

2.6 Arrays and Hashes

Array: In Ruby, the array seems like the list of objects and variables. 

a = [1,2,3,4,5] # Create a array which is full of Integers
a = ["demo", "doheras"] # Also a String array
a[1] #=> doheras
# We can use the official class Array to generate a empty array
a = Array.new
# a << '<The content you want to insert>'
a << 'first item'
puts a # => ['first item']
trolley = ['chips', 'cola', 'chocolate']
# interate the array
trolley.each do |item|
  puts item
end

Hashes - The dictionary in Ruby. (key - value)

prices = {'chips' => 1.5, 'cola'=> 1.89}
prices['chips']
# => 1.5
prices.count
# => 2
Top
Foot