Ruby class class definition
#! / usr / bin / ruby
class Sample
def hello
puts "Hello Ruby!"
end
end
# Use the above class to create the object
object = Sample. new
object.hello
Note
: A function call without arguments can be omitted ()Initialization method Initialization method There is a unified name called Initialize.
class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
end
Ruby variable Ruby supports 5 types
- General lowercase letters, underscores start with: Variables (Variable).
- $ Start: global variable (variable).
- @ begins with: Instance variable (Instance variable).
- @@: Class variable class variables are shared throughout the inheritance chain
- Start of capital Letter: Constant (Constant).
Variables (that is, local variables) variable printing variables can not omit curly braces when printing, other types of variables may omit curly braces, such as you print a variable is the wrong way of writing
a=1
b=2
puts "a: #a"
puts "b: #b"
Print results
A: #ab: #b
The correct wording
a=1
b=2
puts "a: #{a}"
puts "b: #{b}"
Print results
A:1b:2
The lifetime of a variable's life cycle is only in the method, the method is gone, so it can only be defined in the method, such as the wrong way of writing
class Test2
a=1
b=2
def printVar()
puts "a: #{a}"
puts "b: #{b}"
end
end
hellotest = Test2.new
hellotest.printVar()
Output
Test.rb:5:in ' Printvar ': undefined local variable or method ' a ' for #<test2:0x00000002cf2248> (nameerror) from Test.rb:10:in ' <main> '
The correct wording
class Test2
def printVar(a,b)
puts "a: #{a}"
puts "b: #{b}"
end
end
hellotest = Test2.new
hellotest.printVar(1,2)
Output
A:1b:2
The pass-through simple type of a variable is a copy of the value (the string is also a simple object, which is not the same as Java)
class Test2
def testPass(a,b)
puts "before add : a: #{a} b: #{b}"
addVar(a,b)
puts "after add : a: #{a} b: #{b}"
end
def addVar(a,b)
a += 1
b += 2
end
end
hellotest = Test2.new
hellotest.testPass(1,2)
Output
Before add:a: 1 b:2after add:a: 1 b:2
Complex objects are object references
class Obj1
def initialize(a)
@a=a
end
def printVal()
puts "a: #@a"
end
def setA(a)
@a=a
end
def getA()
return @a
end
end
class Test2
def testPass()
testobj = Obj1.new("hello")
a = testobj.getA()
puts "before add : a: #{a}"
addVar(testobj)
a = testobj.getA()
puts "after add : a: #{a}"
end
def addVar(obj)
obj.setA(obj.getA() + " world")
end
end
hellotest = Test2.new
hellotest.testPass()
Output
Before Add:a: helloafter add:a: Hello World
The print instance variable of instance variable instance variable can be printed by omitting curly braces, such as #@a and #{@a} is one thing instance variable life cycle instance variable can only be defined within initialize. If you think this definition in Java is wrong,
class LearnInstanceVar
@a=1
def printVar()
puts "a: #{@a}"
end
end
test1 = LearnInstanceVar.new
test1.printVar
Output
$ Ruby Test.rba:
The right definition
class LearnInstanceVar
def initialize(a)
@a=a
end
def printVar()
puts "a: #{@a}"
end
end
test1 = LearnInstanceVar.new("hello")
test1.printVar
Output
$ Ruby Test.rba:hello
Similar to the private in Java, but more stringent, even the location of the definition can only be placed in a specific method inside
The Print class variable of class variable class variable printing can omit curly braces, such as #@@a and #{@@a} is one thing
Life cycle of class variables
- Class variables can be common across multiple instances, such as Java-like static
- Declaring outside the method body of a class
For example, defining and using class variables
#!/usr/bin/ruby
class Customer
@@no_of_customers=0
def printCus()
@@no_of_customers += 1
puts "Total number of customers : #{@@no_of_customers}"
end
end
cust1=Customer.new
cust2=Customer.new
cust1.printCus()
cust2.printCus()
Global variables
- Global variables begin with the $ symbol
- Global variables can be shared between classes and classes
The ruby operator only says some of Ruby's more special operators compare operators = = and equal? = = and equal are exactly the opposite of what is defined in Java:
- Equal? is to compare whether two objects are the same object
- = = is a comparison of two objects equal
Example
a = "Ruby" # define a string object
b = "Ruby" # Although they are the same as a, they are different objects
a.equal? (b) # false: a and b point to different objects
a == b # true: their content is the same
eq? is equal? Abbreviation <=> Union comparison operator This is a magical operator: the union comparison operator. Returns 0 if the first operand equals the second operand, or 1 if the first operand is greater than the second operand, or 1 if the first operand is less than the second operand. = = = Three equals sign
This operator is more magical:
Typically this is the same as = =, but in some specific cases, = = = has a special meaning:
- in range = = = Determines whether the object to the right of the equal sign contains a range to the left of the equal sign;
- Used in regular expressions to determine whether a string matches a pattern,
- class defines = = = To determine whether an object is an instance of a class,
- Symbol defines = = To determine whether the symbol objects are the same on both sides of the equal sign.
Example:
. eql? Returns true if the receiver and the parameter have the same type and equal values. For example 1 = = 1.0 Returns True, but 1.eql? (1.0) returns FALSE.
Parallel assignment
A = 10b = 20c = 30
Can be written like this
A, b, C = 10, 20, 30
So the cumbersome variable exchange in Java and C can be easily written in Ruby
A, B = B, c
Such a code
a=1
b=2
c=3
a,b=b,c
puts "a: #{a}"
puts "b: #{b}"
puts "c: #{c}"
Execution results are
$ Ruby Test.rba:2b:3c:3
Range operator
- 1..10 creates a range from 1 to 10 and contains 10
- The only difference between 1...10 and the above is that it doesn't contain 10.
Define? Operators we have seen in other languages how to determine whether a variable is defined, such as whether JS is equal to undefined, and PHP Isset,ruby specifically designed for this operation an operator called define? This operator can not only tell you whether the variable is defined but also tells you
Range of VariablesDefined? Variable # True if variable is already initialized
Like what
foo = 42
defined? foo # => "local-variable"
defined? $ _ # => "global-variable"
defined? bar # => nil (undefined)
You can also detect whether a method defines
Defined? Method_call # True if the method is already defined
defined? puts # => "method"
defined? puts (bar) # => nil (here bar is undefined)
defined? unpack # => nil (undefined here)
Ruby dot operator "." and double-colon operator "::" Remember: in Ruby, classes and methods can also be used as constants.
You only need to precede the constant name of the expression with: prefix to return the appropriate class or module object.
If you do not use a prefix expression, the primary Object class is used by default.
Example
MR_COUNT = 0 # Constants defined on the main Object class
module Foo
MR_COUNT = 0
:: MR_COUNT = 1 # set global count to 1
MR_COUNT = 2 # set local count to 2
end
puts MR_COUNT # This is a global constant
puts Foo :: MR_COUNT # This is a local constant for "Foo"
Interesting ruby-Study notes 1