Skip to content

Instantly share code, notes, and snippets.

@hrishimittal
Last active August 29, 2015 14:15
Show Gist options
  • Save hrishimittal/a45d0a429595caad07e3 to your computer and use it in GitHub Desktop.
Save hrishimittal/a45d0a429595caad07e3 to your computer and use it in GitHub Desktop.
Ruby convenience methods
#Given an array, get counts of occurences for each element
#H/T http://jerodsanto.net/2013/10/ruby-quick-tip-easily-count-occurrences-of-array-elements/
def count_array_element_occurences(arr)
arr.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }
end
#Given a hash, convert it to an HTML table
def hash_to_table(h)
t = "<table><thead>"
if h.present?
h[0].keys.each { |k| t+= "<th>" + k.to_s + "</th>" }
t += "</thead><tbody>"
h.each do |r|
t += "<tr>"
r.values.each {|c| t += "<td>" + c.to_s + "</td>" }
t += "</tr>"
end
end
t += "</tbody></table>"
t.html_safe
end
#Clipboard copy and paste
#https://coderwall.com/p/qp2aha/ruby-pbcopy-and-pbpaste
def pbcopy(input)
str = input.to_s
IO.popen('pbcopy', 'w') { |f| f << str }
str
end
def pbpaste
`pbpaste`
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment