Skip to content

Instantly share code, notes, and snippets.

@tiagopog
Last active January 1, 2016 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagopog/0ce3398e200e5f74c351 to your computer and use it in GitHub Desktop.
Save tiagopog/0ce3398e200e5f74c351 to your computer and use it in GitHub Desktop.
Summary of Ruby 2.3's feature.
# frozen_string_literal: true
class User
attr_accessor :admin
def initialize(options = {})
@admin = options[:admin] || false
end
def admin?; @admin end
end
##
# 1. Safe navigation operator
##
user = User.new(admin: true)
if user && user.admin?
puts 'User is admin!'
end
if user&.admin?
puts 'User is admin! (2)'
end
user = nil
if user && user.admin?
puts 'User is admin!'
end
if user&.admin?
puts 'User is admin! (2)'
end
##
# 2. Frozen string literal
##
begin
str = 'foo'
str << 'bar'
rescue
puts 'Strings are frozen by default o/'
end
##
# 3. Array#dig and Hash#dig
##
numbers = [[1, 2], [3, 4], [5, 6]]
puts numbers.dig(2, 1) #=> 6
puts numbers.dig(0, 2) #=> nil
dict = { x: 'foo', y: { z: 'bar' } }
puts dict.dig(:x) #=> "foo"
puts dict.dig(:y, :z) #=> "bar"
puts dict.dig(:y, :w) #=> nil
##
# 4. Hash comparison
##
a = { x: 1, y: 2 }
b = { x: 1 }
puts a >= b #=> true
puts a <= b #=> false
puts b <= a #=> true
##
# 5. Hash#to_proc
##
h = { x: 1, y: 2 }
p = h.to_proc
puts p.call(:y)
puts %i(x).map { |key| h[key] }
puts %i(x).map(&h)
##
# 6. Hash#fetch_values
##
begin
h = { x: 1, y: 2 }
puts h.values_at(:x, :y, :z)
puts h.fetch_values(:x, :y, :z)
rescue KeyError
puts 'Key not found'
end
##
# 7. Enumerable#grep_v
##
puts User.new.methods.grep(/admin/).first
puts User.new.methods.grep_v(/admin/).first
##
# 8. Numeric#positive? and #negative?
##
puts 1.positive?
puts -1.negative?
##
# 9. Did you mean?
##
'foobar'.to_foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment