gpt4 book ai didi

ruby 修改对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:26 24 4
gpt4 key购买 nike

我有代码:

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"

最佳答案

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

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

关于ruby 修改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5419096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com