Skip to content

Instantly share code, notes, and snippets.

@arjunmenon
Last active November 14, 2017 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arjunmenon/bafe7537644a0e3b268dc32f41fb0f6e to your computer and use it in GitHub Desktop.
Save arjunmenon/bafe7537644a0e3b268dc32f41fb0f6e to your computer and use it in GitHub Desktop.
Practical Ruby snippets
  1. Split sentence preserve punctuation
    https://stackoverflow.com/a/15687656/2096740

Use scan (throw strip in there to get rid of trailing spaces).

s = "I am a lion. Hear me roar! Where is my cub? Never mind, found him."
s.scan(/[^\.!?]+[\.!?]/).map(&:strip) # => ["I am a lion.", "Hear me roar!", "Where is my cub?", "Never mind, found him."]

  1. Simple detect puncutation in string
    https://stackoverflow.com/a/5541356/2096740
sub!(/[?.!,;]?$/, '')

  1. Read large files in batches
    https://stackoverflow.com/questions/2962134/ruby-read-file-in-batches
File.open('filename','r') do |f|
  chunk = f.read(2048)
  ...
end

  1. Easy strip HTML/XML tags from string
str = "Remind me to <task>buy milk</task> <time>in one hour</time>"
puts str.gsub(/<\/?[^>]*>/, "")
=> "Remind me to buy milk in one hour"

  1. Keep delimiters when splitting strings
    https://stackoverflow.com/questions/18089562/how-do-i-keep-the-delimiters-when-splitting-a-ruby-string
content = "Do you like to code? How I love to code! I'm always coding." 
content.split(/(?<=[?.!])/)

# Returns an array with:
# ["Do you like to code?", " How I love to code!", " I'm always coding."]

  1. Split string by multiple delimiters
    https://stackoverflow.com/questions/19509307/split-string-by-multiple-delimiters
"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]

  1. Split a string and its punctuation
    https://stackoverflow.com/questions/32037300/splitting-a-string-into-words-and-punctuation-with-ruby
s = "here...is a     happy-go-lucky string that I'm writing"
s.scan(/[\w'-]+|[[:punct:]]+/)
#=> ["here", "...", "is", "a", "happy-go-lucky", "string", "that", "I'm", "writing"]

  1. Search within a two-dimensional array
    https://stackoverflow.com/questions/29745810/how-to-search-within-a-two-dimensional-array
array = [[1,1], [1,2], [1,3], [2,1], [2,4], [2,5]]
array.select{|(x, y)| x == 1}
# => [[1, 1], [1, 2], [1, 3]]

array.select{|(x, y)| x == 1}.map{|(x, y)| y}
# => [1, 2, 3]

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