View
363
Download
0
Category
Preview:
Citation preview
5 RANDOM RUBY TIPSSaigon.rb Ruby Meetup
By Steven Yap6th Oct 2015
• Host Saigon.rb Ruby Meetup• Founder of Futureworkz• Ruby on Rails coder• Agile startup consultant• Pretends to be extrovert• Introvert by nature
Awesome Ruby on Rails Applications for Startupshttp://www.futureworkz.com
https://github.com/futureworkz/playbook
5 RANDOM RUBY TIPS
#1: INTERPOLATE, NOT CONCATENATE
# concatenateputs “error description” + e.cause.to_s + “happened on: ” + Time.now.to_s
#1: INTERPOLATE, NOT CONCATENATE
# interpolateputs "error description #{e.cause} happened on: #{Time.now}"
#1: INTERPOLATE, NOT CONCATENATE
# interpolateputs "error description #{e.cause} happened on: #{Time.now}”
# concatenateputs “error description” + e.cause.to_s + “happened on: ” + Time.now.to_s
#1: INTERPOLATE, NOT CONCATENATE
• Easier to read
• Automatic #to_s
• Type less
#2: AVOID DOUBLE NEGATIVES
# Double negativesunless !post.published? # do somethingend
#2: AVOID DOUBLE NEGATIVES
# Be positive!if post.published? # do somethingend
#2: AVOID DOUBLE NEGATIVES
# Be positive!if post.published? # do somethingend
# Double negativesunless !post.published? # do somethingend
#2: AVOID DOUBLE NEGATIVES
• Much easier to read
• Makes you think more positively
• Makes you happier (like Ruby)
#3: ARRAY.INJECT
# Sum up all numbers in an arrayarray = [1,2,3,4,5]sum = 0array.each do |number| sum += numberend
return sum # => 15
#3: ARRAY.INJECT
# Sum up all numbers in an arrayarray = [1,2,3,4,5]array.inject(0) { |sum, number| sum + number } # => 15
#3: ARRAY.INJECT
# Sum up all numbers in an arrayarray = [1,2,3,4,5]array.inject(0) { |sum, number| sum + number } # => 15
# Sum up all numbers in an arrayarray = [1,2,3,4,5]sum = 0array.each do |number| sum += numberend
return sum # => 15
#3: ARRAY.INJECT
• Easier to read (once you get used to it!)
• Shorter code
• Common Ruby idiom
#4: CHAIN ARRAY METHODS
# Given an array, return a new array with # Only even numbers# The numbers are multiplied by 3# Reject all numbers that are greater than 20
array =[1,2,3,4,5,6,7,8,9,10]
result = []array.each do |x| if x % 2 == 0 result << x * 3 if x * 3 < 21 endend
return result # => [6, 12, 18]
#4: CHAIN ARRAY METHODS
# Given an array, return a new array with # Only even numbers# The numbers are multiplied by 3# Reject all numbers that are greater than 20
array =[1,2,3,4,5,6,7,8,9,10]array.select { |x| x % 2 == 0 }.map { |x| x * 3}.reject { |x| x > 20}# => [6, 12, 18]
#4: CHAIN ARRAY METHODS
• More expressive
• Shorter code
• Common Ruby idiom
#5: ZERO DIVISION ERROR
1/0# ZeroDivisionError: divided by 0
#5: ZERO DIVISION ERROR
1/0.0 # => Infinity
#5: ZERO DIVISION ERROR
• No idea how it can be helpful to you
• But it is fun to know
• Makes you happier (like Ruby!)
THANK YOU
Recommended