在Ruby中,您不能像C语言那样通过引用传递参数。最简单的方法是返回新值,然后分配给输入变量。
film_title = crop_word(film_title)
你可以做的是将film_title放在容器中。
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
我不会推荐它,但你也可以猴子修补String类
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"
最后,还有的eval的black magic和有约束力的,你很可能将不得不疯狂的实际使用。
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
此外,您crop_word
不输出你似乎什么希望,因为它使后面的空格。
考虑调用你的方法'crop_word!'来表明它是可变的。 – 2011-03-24 14:38:31