Skip to content

Instantly share code, notes, and snippets.

View mehdi-farsi's full-sized avatar

Mehdi FARSI mehdi-farsi

View GitHub Profile
# The =~ operator returns the index of the first letter of the first matching occurence
/(rubycademy)/ =~ "https://www.rubycademy.com" # => 12
"https://www.rubycademy.com" =~ /(rubycademy)/ # => 12
# Note that the operator returns nil if no matching found
/lol/ =~ "It's not funny" # => nil
@mehdi-farsi
mehdi-farsi / my_flatten.rb
Last active March 10, 2020 20:02
A not efficient but easy-to-code implementation of Array#flatten
# Flat the array layer by layer
#
# Insights:
#
# - Using recursion.
#
class Array
def my_flatten(depth = nil)
if depth.nil? || depth.is_a?(Fixnum)
Symbol.all_symbols.length # => 3893
Symbol.all_symbols.grep(/Struct/) # => [:Struct]
:dummy_symbol
Symbol.all_symbols.length # => 3894
Symbol.all_symbols.grep(/dummy_symbol/) # => [:dummy_symbol]
dummy_variable = nil
Symbol.all_symbols.length # => 3895
Symbol.all_symbols.grep(/dummy_variable/) # => [:dummy_variable]
for i in 1..3 do
puts "Iteration #{i}"
redo if i == 1
puts 'After redo'
end
# produces:
#
def hello
yield
end
hello do
puts 'hello'
redo
end
[1,2,3].each do |n|
puts "Step #{n}"
n += 1 and redo if n < 2
end
# produces:
#
# Step 1
# Step 2
for i in 1..3 do
puts "Iteration #{i}"
i += 1 and redo if i == 1
end
# produces
#
# Iteration 1
# Iteration 2
class Hash
def to_s
'hash'
end
end
h = {}
p h.to_s # => "hash"
module Patch
@@res = refine(Array) {}
def self.res; @@res; end
end
p Patch.res # => #<refinement:Array@Patch>
p Patch.res.class # => Module
p Patch.res.ancestors # => [#<refinement:Array@Patch>, Array, ...]
@mehdi-farsi
mehdi-farsi / hash.rb
Last active September 8, 2018 21:53
dummy_rails_app
# lib/core_ext/hash.rb
class Hash
# monkey-patch to temporarily
# disabling the MyLib#print_config output
def to_json
''
end
end