ruby修改对象

时间:2011-03-24 12:29:35

标签: ruby

我有代码:

def crop_word (film_title)
  size = film_title.size
  film_title[0...size-2] if size > 4
end

film = "Electrocity"
p crop_word film

如果我想修改对象film,我该怎么办? (我如何创建crop_word方法作为mutator方法?)

p crop_word film #=> "Electroci"
p crop_word film #=> "Electro"
p crop_word film #=> "Elect"

4 个答案:

答案 0 :(得分:3)

def crop_word! (film_title)
  film_title.size > 4 ? film_title.slice!(0..-3) : film_title
end

puts crop_word! "1234567" #=>"12345"

答案 1 :(得分:1)

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

答案 2 :(得分:0)

def crop_word (film_title)
  size = film_title.size
  film_title[size-2..size]="" if size > 4
  film_title
end

通常,您必须使用已经发生就地变异的方法或重新打开相关类并分配给self

答案 3 :(得分:0)

问题不明确。我想你要删除最后一个字符,如果它超过4。

class String
    def crop_word!; replace(self[0..(length > 4 ? -2 : -1)]) end
end


puts 'Electrocity'.crop_word! # => 'Electrocit'