Some tips in ruby
- Assigns the remaining elements of the array
- Change default values in hash
- Raise an exception in the hash
- Operator & when comparing arrays
- Assign multiple values to multiple variables on the same line
- Use | to get all values from two arrays
- Use – to return an element that does not exist in the array
- Swap values
- Use !! when searching in RegEx
- Conclusion
1. Assign the remaining elements of the array
- In the structure of the array we can use * to assign the rest of the array instead of entering values individually
For example:
1 2 3 4 5 6 7 | array = ["a", "b", "c"] val, *otherval = *array val #kết quả: "a" otherval #kết quả: ["b", "c"] array #kết quả: ["a", "b", "c"] |
2. Change the default value in hash
- We can use default and default_proc to change the default value in the hash
Example 1:
1 2 3 4 5 6 7 | hash1={} hash1[:val] #kết quả: nil h.default = "default val" h[:val] #kết quả: "default val" |
Example 2:
1 2 3 4 5 6 7 8 | hash2 = Hash.new do |hash2, name| hash2[name] = Hash.new(&hash2.default_proc) end hash2[:name1][:name2][:name3] = 'big hash' hash2 #kết quả: { name1: { name1: { name1: 'big hash' } } } |
3. Raise an exception in the hash
- Raises an exception when the key in the hash does not exist
For example:
1 2 3 | hash = Hash.new { |h, k| raise ArgumentError.new("the key not found: #{ k }") } hash |