Ruby Getting Started notes
Everything is the object
"Hello". Length
Method
Definition: def start end end
Naming generally uses underscores to separate words
You can embed an expression in a string
return value: A) return+ return value B) function The value of the last line of code is the return value (fantastic)
Class
Definition: Class beginning end end
Initialize is a construction method
The variable at the start of @ is an instance variable (one for each variable)
To_s method can be overloaded
Self. Defining a class method (called with a class name, similar to a class static method, without instantiating an object)
@@ starts with a class variable (like a static variable)
Inheritance of Classes
< represents inheritance
Class Popsong < Song
Def initialize (name, artist, duration, lyrics)
Super (Name, artist, duration)
@lyrics =lyrics
End
End
Super calls the parent class with the same name method
Modular Module
A module is a method of centralizing methods, classes, and constants
Benefits:
- The module provides a namespace to prevent naming conflicts
- The hybrid insertion mechanism enables multiple inheritance through the modular implementation of the mixed insert (mixin) function
Definition: Start with module, End With end
Blocks (block)
An anonymous function, or a closed-packet closure
{puts "Hello World"}
Or
Do
Puts "hi!"
End
I don't know much yet.
Ruby Basic data types
Digital type
How many integers can be displayed, not automatically converted to floating-point type
Operator
+-*/%**
% modulus
* * Power operation
&|^ and/or non-
<<>>[] Left shift right (from low to high)
ABS take absolute value
Ceil/floor/round rounding down, rounding up
Odd?/even?/zero? Odd? Even? Zero? return BOOL Type
Times/upto/downto/step
# Execute N-Times block
5.times {puts "+"} # Print 5 +
# from 1 to 5
1.upto (5) {|i| print I, "+"} # 1+2+: 5+
# reduced from 99 to 95
99.downto (+) {|i| print I, "+"} # 99+: 95+
# from 50 to 80, with 5 as the interval
50.step (5) {|i| print I, "+"} # 50+55+: 80+
String
Double or single quotation marks
Do not escape within single quotation marks
String Typical methods
Size/length/bytesize/empty?
where size and length returns the number of characters
ByteSize returns the number of bytes
+/<< string concatenation
* String Repetition
% formatted output
"%05D"% 123 # "00123"
"%-5s:%08x"% ["ID", 123] # "id:123"
Powerful []
A = "Hello there"
A[1] #=> "E"
a[1,3] #=> "ell"
A[1..3] #=> "ell"
a[-3,2] #=> "ER"
A[-4..-2] #=> "her"
A[12..-1] #=> Nil
A[-2..-4] #=> ""
A[/[aeiou] (.) \1/] #=> "ell"
A[/[aeiou] (.) \1/, 0] #=> "ell"
A[/[aeiou] (.) \1/, 1] #=> "L"
A[/[aeiou] (.) \1/, 2] #=> nil
A["Lo"] #=> "Lo"
A["Bye"] #=> Nil
It's amazing, a lot of people don't understand
Start_with?/end_with?/include?
# does it start with he
"Hello World". Start_with? "He" # True
# Whether to end with LD
"Hello World". End_with? "LD" # True
# Does it contain hi
"Hello World". Include? "HI" # False
Upcase/downcase/swapcase/capitalize
Puts "Hi, Ruby". UpCase # Hi, Ruby
Puts "Hi, Ruby". Downcase # Hi, Ruby
Puts "Hi, Ruby". Swapcase # Hi,ruby
Puts "hii, Ruby". Capitalize # Hi, Ruby
Encoding/force_encoding/encode
# View the encoding of the string, if the encoding is not GBK, you should pay attention to
Puts "I love Ruby". Encoding # Ascii-8bit
# force conversion encoding, only change the encoding identifier, does not change the content
# (useful when you know it was encoded)
"I love Ruby". Force_encoding ("GBK")
# Suppose a string is UTF-8 encoded and can be encode to GBK
"I love Ruby". Encode ("GBK")
Split/scan
# Cut string array
"1,2,,3,4,". Split (', ') # ["1", "2", "", "3", "4"]
# Scan string array (opposite to split)
A = "Cruel World"
A.scan (/\w+/) # ["Cruel", "World"]
A.scan (/(..) (..) /) # [["Cr", "UE"], ["L", "Wo"]]
A.scan (/\w+/) {|w| print "<<#{w}>>"}
# <<cruel>> <<world>>
Strip/rstrip/lstrip
# Remove whitespace next to string
"Hello". Lstrip # "Hello"
"Hello". Rstrip # "Hello"
"Hello". Strip # "Hello"
each_char/each_byte/each_line/
# traversing characters
"Hello". Each_char {|c| print C, '}
# h e l l o
# traversing bytes
"Hello". Each_byte {|c| print C, '}
# 104 101 108 108 111
# Traverse each row
"Hello\nworld". Each {|s| P s}
#
"Hello\n"
"World"
Array
Said
[3.14159, "Pie", 99] # Brackets
Array.new # equivalent to []
%w{haha xixi hoho} #%w way to define a string array
The type of membership in Ruby's array (and other collections) does not have to be the same, which is the legendary heterogeneous
Typical methods
+/-/*/&/<<
# + equals concat
[1, 2, 3] + [4, 5] #=> [1, 2, 3, 4, 5]
#-A set minus all the elements in the B collection
[1, 1, 2, 2, 3, 3, 4, 5]-[1, 2, 4] #=> [3, 3, 5]
[1, 2, 3] * 3 #=> [1, 2, 3, 1, 2, 3, 1, 2, 3]
# Two The intersection of an array
[1, 1, 3, 5] & [1, 2, 3] #=> [1, 3]
# push an object into the array
[1, 2] << "C" << "D" << [3, 4]
#=> [1, 2, "C", "D", [3, 4]]
[]
# [] There are three ways to use
A = ["A", "B", "C", "D", "E"]
A[2] + a[0] + a[1] #=> "Cab"
A[6] #=> Nil
A[1, 2] #=> ["B", "C"]
A[1..3] #=> ["B", "C", "D"]
A[4..7] #=> ["E"]
A[6..10] #=> Nil
A[-3, 3] #=> ["C", "D", "E"]
# Special Cases
A[5] #=> Nil
A[5, 1] #=> []
A[5..10] #=> []
Find/find_all
# Find to one return, alias detect
(1..100). Find {|i|
I% 5 = = 0 and i% 7 = = 0
}
#=> 35
# Find_all Find all eligible objects, alias Select
(1..100). Find_all {|i|
I% 5 = = 0 and i% 7 = = 0
}
#=> [35,70]
First/last/join
A = ["Q", "R", "s", "T"]
# first Element
A.first #=> "Q"
A.first (2) #=> ["Q", "R"] first two elements
# The last element
A.last #=> "T"
# turn the array into a string
["A", "B", "C"].join #=> "abc"
["A", "B", "C"].join ("-") #=> "A-b-c"
Inject/collect
# The difficulty with inject understanding is that the two parameters in the block
# sum is the return value of the last block, initialized to 0 or nil
# n is a traversal of every element of an array
[5,6,7,8,9,10].inject {|sum, n| sum + n} #=> 45
Output 45
Traverse
# collect alias map, traversing arrays and changing their contents after output
A = ["A", "B", "C", "D"]
A.collect {|x| x + "!"} #=> ["a!", "b!", "c!", "d!"]
Each/each_with_index/cycle
# traversing elements
A = ["A", "B", "C"]
A.each {|x| print x, "--"} iterates over the element output, separated by-
# traversing an element with a subscript the first parameter is an array value, the second parameter is the subscript
A.each_with_index {|obj, i| print "A[#{i}]: #{obj}"}
# loop An array
a.cycle {|x| puts x} # Print, A, B, C, a, B, C,.. Forever.
A.cycle (2) {|x| puts X} # Print, A, B, C, a, B, C.
Delete/delete_if/insert/pop/push
# Delete all B-strings
A = ["A", "B", "B", "B", "C"]
A.delete "B" # b
# Delete an element that satisfies a condition
a.delete_if {|x| x >= "B"} # ["A"]
# Insert an object before a sequence
A.insert (2, "B1") # ["A", "B", "B1" ...
# pop and push combine to make an array directly as a stack
A.pop # "C"
A.push "D"
Sort/uniq/shuffle/shift
# Auto Sort
["B", "C", "a"].sort # ["A", "B", "C"]
# Go Heavy
["A", "a", "B", "B", "C"]. Uniq # ["A", "B", "C"]
# Random Change Shuffle ~
A = [1, 2, 3]
A.shuffle # [2, 3, 1]
A.shuffle # [1, 3, 2]
#shift是神马?
Hashed Hash
Said
[] represents the array, {} means hash is the same as Perl?
{"Foo" =>123, "Bar" =>456} # Curly Brace
Typical methods
[]/[]=
# take the value of a key in a hash
H = {"A" = +, "b" = 200}
H["a"] #=> 100
H["C"] #=> Nil
# object with Hash set
H["a"] = 9
H["C"] = 4
H #=> {"A" =>9, "B" =>200, "C" =>4}
Has_key?/has_value?
# Verify that there is a key in the hash
H = {"A" = +, "b" = 200}
H.has_key? ("a") #=> true
#验证Hash中是否存在某value
H.has_value? (999) #=> false
Each/each_key
# take the value of a key in a hash
H = {"A" = +, "b" = 200}
H.each {|key, value| puts "#{key} is #{value}"}
H.each_key {|key| puts key}
*each If only one argument is taken, each key value pair is
H.each {|key| puts "#{key}"}
Delete/delete_if/select
# Delete a key
H = {"A" = +, "b" = 200}
H.delete ("a") #=> 100
# Delete only those that meet the criteria
h.delete_if {|key, value| key >= "B"}
# Pick out the elements
H = {"A" = +, "b" = +, "c" = 300}
H.select {|k,v| v < 100} #=>
Scope Range
Said
.. equivalent to []
... equivalent to [)
1..10 # contains 10
1...10 # does not contain 10
' A ' ... ' Z ' # Letters from A to Z
0...anarray.length
Typical methods
To_a/begin/end
# Expand the Range
(1..7). to_a #=> [1, 2, 3, 4, 5, 6, 7]
# Take the head
(1..7). Begin #=> 1
# Take the tail
(1..7). End #=> 7
===/include?
# = = = is used primarily in case-when statements, which are equivalent to finding a value in range
# Same as the include results
("A" ... " Z "). Include? ("G") # = True
("A" ... " Z ") = = = (" G ") # = = True
each
# Expand the Range
(10..15). Each do |n|
Print N, '
End
# = "10 11 12 13 14 15
Regular expression RegExp
Said
A = Regexp.new (' ^\s*[a-z] ') #/^\s*[a-z]/
b =/^\s*[a-z]/# Two Slash is the simplest notation
c =%r{^\s*[a-z]} #/^\s*[a-z]/
d =%r<^\s*[a-z]> #/^\s*[a-z]/
Typical methods
=~,!~,
#确定匹配
/a/=~ "Fats Waller" # True
# match is an alias for =~
/a/.match "Fats Waller" # True
# negative Match
/z/!~ "Fats Waller" # False
An expression
Conditional control if (note elsif)
If Count > 10
Puts "Try again"
elsif tries = = 3
Puts "You Lose"
Else
Puts "Enter a number"
End
Conditional control unless
Unless is equivalent to if not, meaning: unless or if not
Puts "OK" unless count > 10
True or False
Only false and nil are false, the rest are true
Puts "not execute" if nil
Puts "execute" if 1
Puts "execute" if 0
Puts "not execute" if False
Puts "execute" if True
Puts "execute" if ""
Puts "execute" if array.new
Case...when
In fact, we are familiar with the switch case, but a little more advanced
For example:
Case Lead Status
When "Coma"
Print "You're unconscious."
When "poisoning"
Print "You are poisoned."
When "Lethargy"
Print "You are asleep."
Else
Print "Unknown state"
End
No more break after every
General comparison operators
Cycle
While means the circle of the Earth people know that Ruby inside until can also be used to loop, meaning and while the opposite, until the condition is true, just stop the operation
While I <= 60
# ...
End
Equivalent to
Until I > 60
# ...
End
Transferred from: http://www.cnblogs.com/lunashang/archive/2012/05/07/2487600.html
Ruby Getting Started notes