I,
Ruby Introduction:Ruby is "an interpreted scripting language for quick and easy object-oriented programming ". 1. interpreted scripting language
-
- Ability to make operating system CILS directly
- Powerful string operations and regular expressions
- Immediate feedback during development
2. Quick and easy
-
- Variable declarations are unnecessary
- Variables are not typed
- Memory management is automatic
3. Object Oriented Programming
II,Variables & constant:
1. Variables
-The scope of a local variable is one of Proc {...} /loop {...}. def... end/class... end/module... end
-It can be referred to from anywhere in a program. Before initialization, a global variable has the special value nil.
-Its scope is confined to whatever object self refers.
-Same as the static member in C # language. Note: Don't use the ruby keyword when define a variable.
2. Constant
Definition:
- A constant has a name starting with an uppercase character.
- Constants may be defined within Classes or Module, never in method.
- It shoshould be assigned a value at most once.
E.g .:
Class Demo
PI = 1, 3.1415
# PI = 3.15214 # warning: already initialized constant PI
Def hello
PI = 3.1415 # wrong
End
End
Demo = Demo. new
Demo. hello
III,Comment
• Single line:
# (Ctrl + /)
• Multi-line
= Begin
...
...
= End
IV,Numeric:
- Methods:
- To_f () # Integer-> Float
- To_ I () # Float-> Integer, directly delete the part of decimal, if don't want this, you can use the round method
- Round
- N. times {| I | ...}
- From. upto (to) {| I | ...}
- From. downto (to) {| I | ...}
- From. step (to, step) {| I | ...}
• Additional:
A = 01123 #0 => octal
B =-0x23 # 0x => hex
C = + 0b1010 #0 => binary
V. Range:
1. Definition:
-
- Val1.. val2 # contains: val1 ,..., Va2
- Val1... Val2 # contains: val1 ,..., Val2-1
E. g.: 1 .. 5 # contains: 1, 2, 3, 4, 5 1... 5 # contains: 1, 2, 3, 4
2. Methods:
-
- To_a () # convert to array
- Include? (Targetvalue) // === (targetvalue) # judge whether contains the targetvalue
- Min ()/begin ()/First () # Get the minimum value
- Max ()/end ()/last # Get the maximum value
- Reject: convert to an array and select some element whichdon't satisfy the conditional
- Select: convert to an array and only select some element whichsatisfy the conditional
- Each: iterates over the elements and passing each in turn to the block.
E.g.
A = 10 .. 20
Puts a. Reject {| x <15}
Puts
Puts a. Select {| x <15}
Puts
A. Each {| x | puts x}