1. quickly obtain the matching value of a regular expression
We usually use a regular expression to match the expression first and then obtain the result, but sometimes an exception is thrown. See the following example:
Copy codeThe Code is as follows:
Email = "Fred Bloggs"
Email. match (//) [1] # => "fred@bloggs.com"
Email [//, 1] # => "fred@bloggs.com"
Email. match (/(x)/) [1] # => NoMethodError [:(]
Email [/(x)/, 1] # => nil
Email [/([bcd]). *? ([Fgh])/, 2] # => "g"
In the above example, another simpler method is to use the String # [] method to directly match the regular expression, which is more concise, although it seems to use a devil number.
Of course, you can omit the devil number, if it only matches once:
Copy codeThe Code is as follows:
X = 'this is a Test'
X [/[aeiou]. +? [Aeiou]/] # => 'is I'
In this example, we match the rule "match a vowel first, then a consonant, and then a vowel ".
2. Array # join! Quick implementation
We know that the * operation of Array is to multiply the elements in the Array:
Copy codeThe Code is as follows:
[1, 2, 3] * 3 = [1, 2, 3, 1, 2, 3, 1, 2, 3]
But what will happen when the multiplication factor is not a number or a string?
Copy codeThe Code is as follows:
% W {this is a test} * "," # => "this, is, a, test"
H = {: name => "Fred",: age => 77}
H. map {| I * "="} * "n" # => "age = 77 nname = Fred"
By the way, this is join! . Therefore, you can use this method to quickly implement join! Operation.
3. Quick format of decimal numbers
The sprintf function is usually used for formatting the precision display of floating point numbers, but there is a quicker way to use strings.
Copy codeThe Code is as follows:
Money = 9.5.
"%. 2f" % money # => "9.50"
4. Fast String Parsing
In Tip 3, we can see the formatting of numbers. Here we will talk about the shortcut of string format.
Copy codeThe Code is as follows:
"[% S]" % "same old drag" # => "[same old drag]"
Here it means "same old drag" is displayed in.
Let's take a look at the specific formatting method:
Copy codeThe Code is as follows:
X = % w {p hello p}
"% S" % x # =>"
Hello
"
5. recursively delete files and directories
FileUtils provides this method:
Copy codeThe Code is as follows:
Require 'fileutils'
FileUtils. rm_r 'somedir'
Another method is FileUtils. rm_rf, which corresponds to rm-rf on linux.
6. Fast and exhaustive enumeration objects
You can use the * operation to quickly enumerate all the elements in an enumerated object, such as Array and Hash.
Copy codeThe Code is as follows:
A = % w {a B}
B = % w {c d}
[A + B] # => [["a", "B", "c", "d"]
[* A + B] # => ["a", "B", "c", "d"]
Here * The operator priority is lower than the + operator.
Copy codeThe Code is as follows:
A = {: name => "Fred",: age => 93}
[A] #=> [{: name => "Fred",: age => 93}]
[* A] # => [[: name, "Fred"], [: age, 93]
A = % w {a B c d e f g h}
B = [0, 5, 6]
A. values_at (* B). inspect # => ["a", "f", "g"]
7. Remove temporary variables
Sometimes we need to write a temporary variable, such as a temporary Array, in a way that we do not need to define a temporary variable separately:
Copy codeThe Code is as follows:
(Z | = []) <'test'
Of course, this is not a good programming habit. We recommend that you do not use it in a lot of code.
8. Use a non-string or non-Symbol object as the Hash Key
Maybe you have never tried to use a non-String or non-Symbol object as the Hash Key, but it does. Sometimes it is quite useful.
Copy codeThe Code is as follows:
Does = is = {true => 'yes', false => 'no '}
Does [10 = 50] # => "No"
Is [10> 5] # => "Yes"
9. Use and or to combine multiple operations into one row
This technique is used by many skilled Ruby programmers to replace short-line Code such as if and unless.
Copy codeThe Code is as follows:
Queue = []
% W {hello x world}. each do | word |
Queue <word and puts "Added to queue" unless word. length <2
End
Puts queue. inspect
# Output:
# Added to queue
# Added to queue
# ["Hello", "world"]
However, note that if the expression "queue <word" on the left side of "and" returns nil, "puts" Added to queue "will not be executed and should be used with caution. Not recommended for Geek.
10. Determine whether the current Ruby parser is executing its own script
Sometimes you may need to determine whether the current runtime environment is in your Ruby script file. You can use:
Copy codeThe Code is as follows:
If _ FILE _ = $0
# Do something .. run tests, call a method, etc. We're direct.
End
11. quickly assign values to variables in batches
The most common method to assign values to multiple variables is:
Copy codeThe Code is as follows:
A, B, c, d = 1, 2, 3, 4
You can assign values in batches in a function by passing the * parameter:
Copy codeThe Code is as follows:
Def my_method (* args)
A, B, c, d = args
End
You can also set member variables in batches:
Copy codeThe Code is as follows:
Def initialize (args)
Args. keys. each {| name | instance_variable_set "@" + name. to_s, args [name]}
End
12. Use range to replace complex numeric size comparison
To compare if x> 1000 & x <2000, use the following method:
Copy codeThe Code is as follows:
Year = 1972
Puts case year
When 1970 .. 1979: "Seventies"
When 1980 .. 1989: "Eighties"
When 1990 .. 1999: "Nineties"
End
13. Use enumeration to replace repeated code
Code writing is the most taboo. In Ruby, many files may be require. You can use the following method to save repeated require:
Copy codeThe Code is as follows:
% W {rubygems daemons eventmachine}. each {| x | require x}
14. Ternary operations
Like other languages, Ruby has three-way operations:
Copy codeThe Code is as follows:
Puts x = 10? "X is ten": "x is not ten"
# Or .. an assignment based on the results of a ternary operation:
LOG. sev_threshold = ENVIRONMENT =: development? Logger: DEBUG: Logger: INFO
15. nested ternary operations
Copy codeThe Code is as follows:
Qty = 1
Qty = 0? 'None': qty = 1? 'One': 'shanghai'
# Just to iterate strate, in case of confusion:
(Qty = 0? 'None': (qty = 1? 'One': 'region '))
16. Several implementations of true and false are returned.
The most common is:
Copy codeThe Code is as follows:
Def is_odd (x)
# Wayyyy too long ..
If x % 2 = 0
Return false
Else
Return true
End
End
It can be concise:
Copy codeThe Code is as follows:
Def is_odd (x)
X % 2 = 0? False: true
End
It can also be simpler:
Copy codeThe Code is as follows:
Def is_odd (x)
# Use the logical results provided to you by Ruby already ..
X % 2! = 0
End
Of course, sometimes you worry about the returned nil (the determination rule in ruby is that nil is false, and others are true), then you can display the conversion:
Copy codeThe Code is as follows:
Class String
Def contains_digits
Self [/d/]? True: false
End
End
17. view the exception Stack
Copy codeThe Code is as follows:
Def do_division_by_zero; 5/0; end
Begin
Do_division_by_zero
Rescue => exception
Puts exception. backtrace
End
18. convert an object to an array
* The operator can convert an object into an array object.
Copy codeThe Code is as follows:
1.9.3p125: 005> items = 123456
=> 123456
1.9.3p125: 006> [* items]
=> [123456]
1.9.3p125: 007> [* items]. each do | I | puts I end
123456
=> [123456]
19. No rescue block for begin
The code for capturing exceptions in Ruby is begin... rescue ...:
Copy codeThe Code is as follows:
Def x
Begin
#...
Rescue
#...
End
End
However, rescue can have no begin:
Copy codeThe Code is as follows:
Def x
#...
Rescue
#...
End
20. Block comments
The block code comments in C and Java are/**/, and ruby also has similar block comments:
Copy codeThe Code is as follows:
Puts "x"
= Begin
This is a block comment
You can put anything you like here!
Puts "y"
= End
Puts "z"
21. Throw an exception
Throw is used to throw exceptions in Java. ruby is more flexible. You can directly throw exceptions in a line of code without interrupting the current call Stack:
Copy codeThe Code is as follows:
H = {: age => 10}
H [: name]. downcase # ERROR
H [: name]. downcase rescue "No name" # => "No name"