在 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 和 binding 的 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 不会输出您想要的内容,因为它保留了尾随空格。