Skip to content

Instantly share code, notes, and snippets.

module IntegerExtension
def to_s
"this is an integer: #{super}"
end
end
Integer.prepend(IntegerExtension)
puts 1.to_s
client = {client: { firstname: "bobby", lastname: "brown"}}
# Using the the [] getter
firstname = client[:client][:firstname]
=> "bobby"
# Using the new dig method, it gives you the
# same result the best is coming
firstname = client.dig(:client, :firstname)
=> "bobby"
# This refinement will monkey patch the Integer#to_s method
# this change will be applied only in the current context
module IntegerRefinement
refine Integer do
def to_s
"this is an integer: #{super}"
end
end
end
@pointcom
pointcom / array.rb
Last active January 24, 2018 10:22
# You can create an array of one string element with *
my_array = *"hello"
=> ["hello"]
arr = %w(a b c)
=> ["a", "b", "c"]
head, *tail = arr
=> ["a", "b", "c"]
name = "Stuart"
# To build a string and escape double quote at the same time
%q(Hello, my name is "#{name}")
=> "Hello, my name is \"\#{name}\""
# The same exist for single quote
%Q(Hello, my name is "#{name}")
=> "Hello, my name is \"Stuart\""
# http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-min
# Ruby 2.2
[1, 2, 3, 4, 5].min(2)
=> [1, 2]
[3, 4, 5].max(3)
=> [5, 4, 3]
# Ruby >= 2.2
mystring = "Hello World"
mystring&.upcase
=> "HELLO WORLD"
mystring = nil
mystring&.upcase
=> nil
# http://ruby-doc.org/core-2.5.0/Float.html#method-i-round
# Ruby >= 2.4
(2.5).round(half: :up)
=> 3
(2.5).round(half: :down)
=> 2
# http://ruby-doc.org/core-2.5.0/MatchData.html#method-i-named_captures
# Ruby >= 2.4
/(?<first_name>.+) (?<last_name>.+)/.match('Bobby Brown').named_captures
=> {"first_name"=>"Bobby", "last_name"=>"Brown"}
# http://ruby-doc.org/core-2.5.0/MatchData.html#method-i-named_captures
# Ruby >= 2.4
/(?<first_name>.+) (?<last_name>.+)/.match('Bobby Brown').named_captures