In Ruby you can't pass parameters by reference like in C-like languages. The easiest way is to return the new value and then assign in to the input variable.
film_title = crop_word(film_title)
What you can do is to place the film_title in a container.
class Film
attr_accessor :title, :length
end
film = Film.new
film.title = "Butch Cassidy and the Sundance Kid"
def crop_word (film)
length = film.title.length
film.title=film.title[0..length-2] if length > 4
end
puts crop_word(film)
# Butch Cassidy and the Sundance K
puts crop_word(film)
# Butch Cassidy and the Sundance
puts crop_word(film)
# Butch Cassidy and the Sundan
I wouldn't recommend it but you could also monkey patch the String class
class String
def crop_word!
self.replace self[0..self.length-2] if self.length > 4
end
end
title = "Fear and Loathing in Las Vegas"
title.crop_word!
# => "Fear and Loathing in Las Vega"
title.crop_word!
# => "Fear and Loathing in Las Veg"
title.crop_word!
# => "Fear and Loathing in Las Ve"
Finally there's the black magic of eval and binding which you probably would have to be insane to actually use.
def crop_word(s, bdg)
eval "#{s}.chop!.chop! if #{s}.length > 4", bdg
end
title="The Dark Knight"
crop_word(:title, binding)
puts title
# The Dark Knig
crop_word(:title, binding)
puts title
# The Dark Kn
crop_word(:title, binding)
puts title
# The Dark
Also, your crop_word
does not output what you seem to want since it keeps the trailing spaces.