Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Zeke Sikelianos

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Ruby word count

   1  
   2  module StringExtensions
   3    def words
   4      s = self.dup
   5      s.gsub!(/\w+/, 'X')
   6      s.gsub!(/\W+/, '')
   7      s.length
   8    end
   9  end

Fancy little ruby input prompter

   1  
   2  for i in 1..100
   3    print "Now at #{i}. Restart? "
   4    retry if gets =~ /^y/i
   5  end

File extension regex

   1  
   2  # returns nil if not found or numerical index if found
   3  "dog.jpg" =~ /.*(jpg|png|gif)$/
   4  
   5  validates_format_of :image_url, :with => %r{\.(gif|jpg|png)$}i


Rails Regex: Convert spaces to dashes

   1  
   2  s.gsub!(/\ +/, '-')

Rails Regex Lookaround

(Snagged from http://www.pivotalblabs.com/articles/2007/09/11/string-split-and-regex-lookarounds)

Ruby supports regular expression quite well, so it's not surprising that one can use a lookaround to match a specific position. That also works really well with String#split, so if one needs to extract the key/value out of a string such as this:

   1  
   2  s = "TYPE=Exterior RED=119 GREEN=105 BLUE=88 TABLEREQ=PNTTBL-01 TABLE=Primary w/XL GENERICCLR=Beige GENERICCLRCODE=31"
   3  s.split(/\s(?=[A-Z]*=)/)


Just splitting on "space" won't work because there are spaces inside the values, too ("Primary w/XML"). Simple and useful...

Ruby: Strip html tags from a string

   1  
   2  str = "<html>This and <b>that</b> and <br />and <span class='something'>the other</span>?<html>"
   3  puts str.gsub(/<\/?[^>]*>/, "")
   4  

Ruby: Count number of words in a string

   1  
   2  class String
   3    def count_words
   4      n = 0
   5      scan(/\b\S+\b/) { n += 1}
   6      n
   7    end 
   8  end

Testing for Exception message in Rails

   1  
   2  e = assert_raise(RuntimeError) { my_code_that_raises }
   3  assert_match(/Error message here/i, e.message)..
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS