Ruby Tricks


1. Object#tap
If you have a method which updates one key in hash, you need to add return that hash in the
end of method.



But you can use Object#tap !



The result will be equal

2. bsearch
If you need to use "find" in a big sorted Array, change method to bsearch



        user        system      total        real
find      3.020000   0.010000   3.030000   (3.028417)
bsearch  0.000000   0.000000  0.000000   (0.000006)


3. Flat_map
If you have two or more "map" methods, and as a result you get multidimensional array like [[1,2], [[3],4]]].

[[['Ben', 'Sam', 'David'], ['Keith']], [[], [nil]], [['Chris'], []]]
What can you do? You can use method flatten after each "map"


But it will be shorter to use "flat_map" instead of "map"




4. new Array
Quickly create two-dimensional array with zeros

5.  Comparison
You can use comparison "<=>" for time issue. If you pass time in minutes and return hours.



6. Deep copy
object.clone - give you the same object, scilicet reference
Marshal.dump(obj) - give you a new object (new object_id)

7. Rub Ruby
How to run code in terminal without creating ruby file?
ruby -e "code_here"
8. Quick bool
Concert any value to the Boolean
!!(1)   # true
!!(nil) # false

9. What is "and"
Code

code: d = 1 and e = 2 and false and f = 3
result d = 1 e = 2 f = nil


Info from
blog.engineyard.com


Comments