1. Quickly get matching values for regular expressions
Usually we use regular expressions, which are match first, and then we take the result, but sometimes we throw an exception, and look at the following example:
Copy Code code 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"
An easier way to do this is to use the String#[method to directly match regular expressions, even more succinctly, although it looks like the devil number is used.
Of course you can omit that demon number if only one match is used:
Copy Code code as follows:
x = ' This is a test '
x[/[aeiou].+?[ aeiou]/] # => ' is I '
In this example, we match the rule "to match a vowel, then a consonant, and then a vowel."
2. Fast implementation of array#join!
We know that the array's * operation is to multiply the elements in the array:
Copy Code code as follows:
[1, 2, 3] * 3 = [1, 2, 3, 1, 2, 3, 1, 2, 3]
But what happens when multiplicative factors are not numbers or strings?
Copy Code code as follows:
%w{this is a test} * "," # => "This, is, a, test
h = {: Name => "Fred",: Age => 77}
H.map {|i| I * "="} * "n" # => "age=77nname=fred"
By the way, this is the effect of join!. Therefore, the join! operation can be implemented quickly in this way.
3. Quickly format decimal digits
The precision display of the formatted floating-point number usually uses the sprintf function, but there is a quicker way to use the string.
Copy Code code as follows:
Money = 9.5
"%.2f"% Money # => "9.50"
4. Quick Parse String
In tip 3 We see the formatting of numbers, and here's a shortcut to the string format.
Copy Code code as follows:
' [%s] '% ' same old drag # => ' [same old drag] '
The meaning here is to display "same old drag" in [].
Let's take a look at the specific formatting methods:
Copy Code code as follows:
x =%w{p Hello P}
'%s '% x # => '
Hello
”
5. Recursively delete files and directories
Fileutils provides this method:
Copy Code code as follows:
Require ' fileutils '
Fileutils.rm_r ' Somedir '
Another method is FILEUTILS.RM_RF, which corresponds to the RM-RF on Linux.
6. Fast and exhaustive enumerable objects
Use the * operation to quickly and easily enumerate all the elements in an enumerable object, such as Array,hash objects.
Copy Code code as follows:
A =%w{a B}
b =%w{c D}
[A + b] # => [["A", "B", "C", "D"]]
[*a + b] # => ["A", "B", "C", "D"]
Here * The precedence of the operator is lower than the + operator.
Copy Code code 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. Eliminate temporary variables
We sometimes need to write a temporary variable like a temporary array, there is a way to not define a temporary variable individually:
Copy Code code as follows:
Of course this is not a good programming habit, it is recommended not to use a lot of code.
8. Use a non-string or non-symbol object as a hash key
Maybe you've never tried using a non-string or a symbol object as a hash key, but it's OK and sometimes useful.
Copy Code code as follows:
does = is = {true => ' Yes ', false => ' No '}
Does[10 = =] # => "No"
Is[10 > 5] # => "Yes"
9. Combine multiple operations into one line using and OR OR
This technique is used by many skilled ruby programmers to replace the short line of code such as if and unless.
Copy Code code 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"]
But note that this way, if and left expression "queue << word" returns nil "puts" Added to queue "" will not be executed, use caution. Not geek recommend not to use.
10. Determine if the current Ruby parser is executing its own script
Sometimes you might want to determine whether your current running environment is in your Ruby script file, and you can use:
Copy Code code as follows:
If __file__ = $
# do something. Run tests, call a method, etc. We ' re direct.
End
11. Assign values to variables quickly and in batches
The most commonly used variable assignment methods are:
Copy Code code as follows:
You can assign values in bulk in a function by passing the parameters of the *:
Copy Code code as follows:
def my_method (*args)
A, B, c, d = args
End
You can also set member variables in bulk:
Copy Code code 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 comparisons
If you want to compare if x > 1000 && x < 2000, you can replace it with the following:
Copy Code code as follows:
Year = 1972
Puts case year
When 1970..1979: "Seventies"
When 1980..1989: "Eighties"
When 1990..1999: "Nineties"
End
13. Replace duplicate code with enumeration operation
Write code is the most taboo "repeat", in Ruby sometimes require many files, you can use the following way to omit the duplicate require:
Copy Code code as follows:
%w{rubygems daemons Eventmachine}.each {|x| require x}
14. Three-dimensional operation
Ruby, like any other language, has ternary operations:
Copy Code code 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 = =:d evelopment? Logger::D ebug:logger::info
15. Nested three-dimensional operation
Copy Code code as follows:
Qty = 1
Qty = 0? ' None ': Qty = 1? ' One ': ' Many '
# Just to illustrate, in case of confusion:
(Qty = 0?) ' None ': (Qty = 1?) ' One ': ' many ')
16. The realization of several return True,false
The most common is:
Copy Code code as follows:
def is_odd (x)
# wayyyy too long.
If x% 2 = 0
return False
Else
return True
End
End
The simple thing to do is:
Copy Code code as follows:
def is_odd (x)
X 2 = 0? False:true
End
You can also be more concise:
Copy Code code as follows:
def is_odd (x)
# Use the logical results provided to your by Ruby already.
X% 2!= 0
End
Of course, sometimes you worry about returning nil (the rule in Ruby is nil to false, all others are true), then you can display the conversion:
Copy Code code as follows:
Class String
def contains_digits
Self[/d/]? True:false
End
End
17. View the exception stack
Copy Code code 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 to an array object
Copy Code code 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 with begin
The code to catch exceptions in Ruby is begin...rescue ...:
Copy Code code as follows:
def X
Begin
# ...
Rescue
# ...
End
End
But rescue can have no begin:
Copy Code code as follows:
def X
# ...
Rescue
# ...
End
20. Block annotation
Block code comments in C and Java are similar block annotations in/**/,ruby:
Copy Code code as follows:
Puts "X"
=begin
This is a block comment
Can put anything you like here!
Puts "Y"
=end
Puts "Z"
21. Throw an exception
Throwing Exceptions in Java is more flexible in using Throw,ruby, which can throw exceptions directly in one line of code without interrupting the current call stack:
Copy Code code as follows:
H = {: Age => 10}
H[:name].downcase # ERROR
H[:name].downcase Rescue "No Name" # => ' No Name '