Skip to content

Instantly share code, notes, and snippets.

@scdekov
Created January 28, 2019 15:22
Show Gist options
  • Save scdekov/ccf587f2a5ee2943278818e2e70df51e to your computer and use it in GitHub Desktop.
Save scdekov/ccf587f2a5ee2943278818e2e70df51e to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class MegaGreeter
attr_accessor :names
def initialize(names = 'World')
@names = names
end
def say_hi
if @names.nil?
puts '...'
elsif @names.respond_to? :each
@names.each do |name|
puts "hello #{name}"
end
else
puts "hello #{@names}"
end
end
end
def fib(n)
return 0 if n.zero?
return 1 if n < 2
fib(n - 1) + fib(n - 2)
end
def min_max_sum(arr)
[arr.sum - arr.max, arr.sum - arr.min]
end
def merge_sorted(arr1, arr2)
result = []
while !arr1.length.zero? && !arr2.length.zero?
if arr1[0] < arr2[0]
result.push arr1.shift
else
result.push arr2.shift
end
end
result.concat arr1, arr2
end
def merge_sort(arr)
return arr if arr.length < 2
merge_sorted(merge_sort(arr[0, arr.length / 2]),
merge_sort(arr.drop(arr.length / 2)))
end
puts merge_sort([2, 3, 1, 5, 1, 22, 11])
def curry(func, *args)
lambda do |*new_args|
args = args.concat new_args
if args.length == func.arity
func.call(*args)
else
curry func, args
end
end
end
def a(b, c)
puts b, c
end
puts curry(method(:a)).call(1).call.call(2)
@kanevk
Copy link

kanevk commented Jan 28, 2019

https://gist.github.com/scdekov/ccf587f2a5ee2943278818e2e70df51e#file-rb-L60 I would go for one-liner here

args.length == func.arity ? func.call(*args) : curry(func, args)

and also be consistent when using brackets. Better use brackets at most of the places except some simple one as:

puts "some string"

@kanevk
Copy link

kanevk commented Jan 28, 2019

https://gist.github.com/scdekov/ccf587f2a5ee2943278818e2e70df51e#file-rb-L34 better naming than arr1, arr2. Maybe left_arr and right_arr will be better.

@kanevk
Copy link

kanevk commented Jan 28, 2019

I'm concern about mutating args here https://gist.github.com/scdekov/ccf587f2a5ee2943278818e2e70df51e#file-rb-L57. It may not a problem in this situation but using concat with some data that have come from outside isn't a good practice(mutation).

@kanevk
Copy link

kanevk commented Jan 28, 2019

You can use modules as containers for functions.

module M
  def self.baba
    # something
  end
end

M.baba

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