Skip to content

Instantly share code, notes, and snippets.

View EdDeAlmeidaJr's full-sized avatar
🏠
Working from home

Ed de Almeida EdDeAlmeidaJr

🏠
Working from home
View GitHub Profile
@EdDeAlmeidaJr
EdDeAlmeidaJr / flatten.rb
Last active May 13, 2016 11:34
Flatten an array without using Array#flatten
def ints_only?(arr)
res = true
arr.map { |item| res = res && item.is_a?(Integer) ? true : false }
res
end
def array_flatten(arr)
while !ints_only?(arr) do
new_arr = Array.new
arr.map{ |item|
def most_common_letter(string)
h = Hash.new
characters = string.chars.each do |c|
if (h[c].nil?) then
h[c] = 1
else
h[c] = h[c]+1
end
end
maxk = nil
def most_common_letter(string)
h = Hash.new
string.chars.sort.each do |c|
h[c] = 0 if (h[c].nil?)
h[c] = h[c] + 1
end
maxk = nil
maxv = -1
mk = h.keys
mk.each do |k|
def most_common_letter(string)
counts = Hash.new(0)
string.each_char {|c| counts[c] += 1 }
counts.max_by{|k,v| v}
end
@EdDeAlmeidaJr
EdDeAlmeidaJr / method_inside_method_2.rb
Created May 14, 2016 22:28
Example of the behavior of a Ruby method defined inside other method
def alfa
alfa_variable = 1
def beta
beta_variable = 2
puts 'Method beta'
end
puts 'Method alfa'
puts alfa_variable
@EdDeAlmeidaJr
EdDeAlmeidaJr / method_inside_method_1.rb
Created May 14, 2016 22:33
Ruby methods inside methods
def alfa
def beta
puts 'Method beta'
end
puts 'Method alfa'
beta
end
@EdDeAlmeidaJr
EdDeAlmeidaJr / addingrelations01.rb
Last active May 22, 2016 00:12
Adding two ActiveRecord relations - Part 1
class CustomersController < ApplicationController
def index
a = Customer.find(1)
b = Customer.where.not(id: 1).order(:name)
@customers = a + b
end
end
@EdDeAlmeidaJr
EdDeAlmeidaJr / addingrelations02.rb
Last active May 22, 2016 00:18
Adding two ActiveRecord relations - Part 2
class CustomersController < Applicationcontroller
def index
a = Customer.where(id: 1)
b = Customer.where.not(id: 1).order(:name)
@customers = a + b
end
end
@EdDeAlmeidaJr
EdDeAlmeidaJr / addingrelations03.rb
Last active May 22, 2016 00:37
Adding two ActivreRecord relations - Part 3
class CustomersController < ApplicationController
def index
@customers = Array.new
@customers.push(Customer.find(1))
Customer.where.not(id: 1).order(:name).each{ |rec| @customers.push(rec) }
end
end
@EdDeAlmeidaJr
EdDeAlmeidaJr / isprime01.rb
Created June 1, 2016 11:51
A function to tell if a integer is prime or not.
def prime?(n)
res = true
(2..n-1).each{ |d| res = res && (not ((n%d)==0)) }
return res
end