you are in: codestackercodes [RSS] → tag: string [RSS]

trim a string in words Delicious Email

show/hide lines
   1  def trim_by_words(string,wordcount) 
   2    string.split[0..(wordcount-1)].join(" ") +(string.split.size > wordcount ? "..." : "") 
   3  end
   4  
   5  # example
   6  string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
   7  
   8  puts trim_by_words(string,10) # returns: Lorem Ipsum is simply dummy text of the printing and...
created by leozera — 14 December 2008 — get a short url — tags: ruby string embed

ruby string proper case Delicious Email

show/hide lines
   1  test = "hello man! how are you?" 
   2  puts test.split(/\s+/).each{ |word| word.capitalize! }.join(' ')
created by leozera — 14 December 2008 — get a short url — tags: ruby string embed

reads an entire file as string Delicious Email

show/hide lines
   1  def get_file_as_string(filename)
   2    data = ''
   3    f = File.open(filename, "r") 
   4    f.each_line do |line|
   5      data += line
   6    end
   7    return data
   8  end
   9  
  10  test = get_file_as_string 'myfile.txt'
  11  puts test
created by leozera — 01 November 2008 — get a short url — tags: ruby string embed

string manipulation Delicious Email

show/hide lines
   1  # using 'insert'
   2  
   3  myString = "Paris in Spring" 
   4  myString.insert 8, " the"  # returns "Paris in the Spring"
   5  
   6  # using 'gsub' for remove non-alphabetic characters from a string
   7  
   8  myString = "Only a test!!!" 
   9  myString.gsub(/[^a-zA-Z|\s]/,'') # returns "Only a test"
  10  
  11  # using 'gsub' for search & replace
  12  
  13  myString = "I love ASP"
  14  myString.gsub('ASP','Ruby') # returns "I love Ruby"
created by leozera — 07 September 2008 — get a short url — tags: ruby sample string embed