Skip to content

Instantly share code, notes, and snippets.

@denpatin
Created October 1, 2015 16:28
Show Gist options
  • Save denpatin/75c1a2ea9adc29df6e37 to your computer and use it in GitHub Desktop.
Save denpatin/75c1a2ea9adc29df6e37 to your computer and use it in GitHub Desktop.
Ruby hacks

Smart hacks for Ruby

Interpolate arrays

pets = %w[dog cat rabbit]
puts "My first pet is a %s, my second one a %s and my third is a %s" % pets

Boolean confusion

puts "hello" && "world"

and

puts "hello" and "world"

is not actually the same. (Tip: The matter is precedence).

Rescue-begin blocks

def m(arg)
  arg.my_method
rescue => e
 # handle exception here
end

The method declaration is actually a begin block.

Logic hashes

redirection_path = Hash.new{|hash, key| hash[key] = (
                              %w(reviewer admin collaborator).include?(key.to_s) ?
                              instance_eval("#{key}_path") :
                              instance_eval('user_path'))
                            }

@document.save ?
  redirect_to redirection_path[current_user.role.to_sym] :
  (render :new)

Functional power

arr =[1,2,3,4,5,6,7,8,9,10]

new_arr = []
arr.each do |x|
  if x % 2 == 0
    new_arr << x * 3 if x * 3 < 20
  end
end

and

arr.select{|x| x % 2 == 0 }.map{|x| x * 3}.reject{|x| x > 19}

is actually the same.

One more example:

load "project/tasks/annotations.rake"
load "project/tasks/dev.rake"
load "project/tasks/framework.rake"
load "project/tasks/initializers.rake"
load "project/tasks/log.rake"
load "project/tasks/middleware.rake"
load "project/tasks/misc.rake"
load "project/tasks/restart.rake"
load "project/tasks/routes.rake"
load "project/tasks/tmp.rake"
load "project/tasks/statistics.rake" if Rake.application.current_scope.empty?

and

%w[
  annotations
  dev
  framework
  initializers
  log
  middleware
  misc
  restart
  routes
  tmp
].tap { |arr|
  arr << 'statistics' if Rake.application.current_scope.empty?
}.each do |task|
  load "rails/tasks/#{task}.rake"
end

is also the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment