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

trim a string in words

def trim_by_words(string,wordcount) 
  string.split[0..(wordcount-1)].join(" ") +(string.split.size > wordcount ? "..." : "") 

# example

string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."

puts trim_by_words(string,10) # returns: Lorem Ipsum is simply dummy text of the printing and...

ruby string proper case

test = "hello man! how are you?" 
puts test.split(/\s+/).each{ |word| word.capitalize! }.join(' ')

reads an entire file as string

def get_file_as_string(filename)
  data = ''
  f =, "r") 
  f.each_line do |line|
    data += line
  return data

test = get_file_as_string 'myfile.txt'
puts test

string manipulation

# using 'insert'

myString = "Paris in Spring" 
myString.insert 8, " the"  # returns "Paris in the Spring"

# using 'gsub' for remove non-alphabetic characters from a string

myString = "Only a test!!!" 
myString.gsub(/[^a-zA-Z|\s]/,'') # returns "Only a test"

# using 'gsub' for search & replace

myString = "I love ASP"
myString.gsub('ASP','Ruby') # returns "I love Ruby"

Displaying all 4 Code