Skip to content

Instantly share code, notes, and snippets.

Avatar

Steven Talcott Smith stalcottsmith

View GitHub Profile
@stalcottsmith
stalcottsmith / gist:9481995
Created Mar 11, 2014
quick naive is_substring implementation
View gist:9481995
def is_substring?(s1, s2)
match = false
if s2.length > s1.length
s1_chars, s2_chars = s1.split(''), s2.split('')
possible_matches = []
s2_chars.each_with_index do |c, i|
possible_matches << [c, i] if c == s1_chars.first
end
possible_matches = possible_matches.map {|c,i| s2_chars.slice(i,s1.length).join}
match = possible_matches.any? {|candidate| candidate == s1 }
@stalcottsmith
stalcottsmith / gist:1b74155cbfe3a23d8573
Last active Aug 29, 2015
My go-to solution for random id numbers which programmers frequently need
View gist:1b74155cbfe3a23d8573
# yields an 11 digit number in base-36
# with an equal probability distribution for all digits
(0..10).to_a.map {(rand*36).to_i.to_s(36)}.join
# this is slightly preferable to the more simple
(rand*(36**11)).to_i.to_s(36)
# because any number so generated will occasionally be "short"
# and because the first digit will follow a non-random distribution
# in terms of frequency due to some strange number theory thing
@stalcottsmith
stalcottsmith / GoLangLinks
Last active Aug 29, 2015
Quick study links for reviewing GoLang with an eye toward web development
View GoLangLinks
@stalcottsmith
stalcottsmith / recursive function
Created Jun 13, 2015
Is there an anonymous recursion alternative in Ruby? This is the best I could come up with which requires naming.
View recursive function
func = -> (node, func) {
node.children.each do |node|
# do something
func.call(node, func)
end
}
func.call(root, func)
View gist:330917
module Abbreviator
def self.abbreviate(names)
abbrs = names.sort.inject({}) do |hash, name|
hash[name] = replace_non_word_chars(name).slice(0,3)
hash
end
Hash[*abbrs.map do |name, abbr|
[name,
(abbrs.values.select{|v|v.eql?(abbr)}.size == 1) ? abbr :
@stalcottsmith
stalcottsmith / role.rb
Created Mar 3, 2011
Declarative Auth Role Ancestor hierarchy
View role.rb
class Role < ActiveRecord::Base
require 'declarative_authorization/development_support/analyzer'
has_many :assignments
has_many :users, :through => :assignments
validates :name, :presence => true
validates :name, :uniqueness => true
def ancestors