Sequence calls to code blocks
Copy Code code as follows:
def Touch_down
Yield [3, 7]
Puts "touchdown!"
End
Touch_down do | (First_down, Second_down) |
Puts "#{first_down} yards on the run"
Puts "#{second_down} yards passed"
End
=> "3 yards on the run"
=> "7 yards passed"
=> "touchdown!"
The main is that the use of array in block
To remove an element from an array
Copy Code code as follows:
>> args = [1, 2, 3]
>> a rest = args
>> A
=> 1
>> Rest
=> [2, 3]
It was just clear how the split sequence was used, and we didn't notice that we could easily get the rest of the sequence.
Hash#fetch
Copy Code code as follows:
>> items = {: Apples => 2,: Oranges => 3}
=> items = {: Apples=>2,: Oranges=>3}
>> Items.fetch (: Apples)
=> 2
>> Items.fetch (: bananas) {|key| "We don ' t carry #{key}!"}
=> We don ' t carry bananas!
When hashing is used, fetch may be more convenient than checking for the existence of a value.
To create a hash of a code snippet
Copy Code code as follows:
>> smash = hash.new {|hash, key| hash[key] = "A #{key} just got smashed!"}
=> {}
>> smash[:p Lum] = "Cannot smash."
=> {:p lum=> "cannot smash."}
>> Smash[:watermelon]
=> {:p lum=> "cannot smash.",:watermelon=> "a watermelon just got smashed!"}
Using a snippet to produce a hash makes it easy to maintain some undefined initial values, especially in the Fibonacci calculations (I didn't see how to use them).
Array#sort_by
Copy Code code as follows:
>> cars =%w[beetle Volt Camry]
=> ["Beetle", "Volt", "Camry"]
>> cars.sort_by {|car| car.size}
=> ["Volt", "Camry", "Beetle"]
The Sort_by method of the sequence is used to sort the return value of the code snippet, just as for the Symbol#to_proc map or sort
String#present?
Copy Code code as follows:
>> "Brain". Present?
=> true
>> "". Present?
=> false
The rails developer might be able to do it for blank? More familiar, but for present? It's also a good way to actually determine if the return value is correct.
Here I do think about the difference between find (: All) and see (: a) whether there is a return value. There is also a
. exists?
. Empty?
. Blank?
. Nil?
See more.