2011-03-24 155 views
1

我有代码:红宝石修改对象

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方法作为赋值函数方法?)

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

考虑调用你的方法'crop_word!'来表明它是可变的。 – 2011-03-24 14:38:31

回答

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

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

是否应该返回'nil''除非size> 4''? – sawa 2011-03-24 14:49:09

+0

@sawa:呃,没有。纠正。 – steenslag 2011-03-24 15:03:45

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

一般来说,你要么必须使用已经不就地突变的方法或重新打开相关类,并分配给self

+0

谢谢!它帮助到我。 – maxfry 2011-03-24 12:56:05

+0

不要忘了点击接受按钮(答案左边的复选标记)。 – 2011-03-24 12:58:55

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不输出你似乎什么希望,因为它使后面的空格。

+0

对不起,这只是错误的。这里不需要包装器,String#切片!方法会很好地完成这项工作。 – regularfry 2011-03-24 16:12:27

+0

当然,这并不意味着是字符串切片的解决方案,而是意味着更广泛地解释Ruby具有什么而不​​是参考/输出变量。 – 2011-03-24 18:49:01

0

问题不明确。我想你想删除最后一个字符,如果它大于4.

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


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