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.

def update_params(params)
params[:foo] = 'bar'
params
end


But you can use Object#tap !

def update_params(params)
params.tap { |p| p[:foo] = 'bar' }
end


The result will be equal

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

require 'benchmark'
data = (0..50_000_000)
Benchmark.bm do |x|
x.report(:find) { data.find {|number| number > 40_000_000 } }
x.report(:bsearch) { data.bsearch {|number| number > 40_000_000 } }
end


        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]]].

module CommentFinder
def self.find_for_users(user_ids)
users = User.where(id: user_ids)
users.map do |user|
user.posts.map do |post|
post.comments.map |comment|
comment.author.username
end
end
end
end
end
[[['Ben', 'Sam', 'David'], ['Keith']], [[], [nil]], [['Chris'], []]]
What can you do? You can use method flatten after each "map"
module CommentFinder
def self.find_for_users(user_ids)
users = User.where(id: user_ids)
users.map { |user|
user.posts.map { |post|
post.comments.map { |comment|
comment.author.username
}.flatten
}.flatten
}.flatten
end
end


But it will be shorter to use "flat_map" instead of "map"
module CommentFinder
def self.find_for_users(user_ids)
users = User.where(id: user_ids)
users.flat_map { |user|
user.posts.flat_map { |post|
post.comments.flat_map { |comment|
comment.author.username
}
}
}
end
end




4. new Array
Quickly create two-dimensional array with zeros
Array.new(8)
{ Array.new(8) { ‘0’ } }

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


def fix_minutes
until (0...60).member? minutes
@hours -= 60 <=> minutes
@minutes += 60 * (60 <=> minutes)
end
@hours %= 24
self
end

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