Last active
August 29, 2015 14:15
-
-
Save hrishimittal/a45d0a429595caad07e3 to your computer and use it in GitHub Desktop.
Ruby convenience methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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