使用克隆时如何消除 ruby 中的重复?
此方法只是更改找到的任何player_id 的id。 Reek 讨厌它,但我找不到一种方法以有意义的方式重构它。
(1..9).each { |n|
n = n.to_s
self.player_ids[n] = self.site_id.clone << "_" << self.player_ids[n].clone if self.player_ids[n]
}
我是否必须忍受这种重复,因为克隆功能不允许我:
player_id = self.player_ids[n]
player_id = self.site_id.clone << "_" << player_id.clone if player_id
示例输入:
{:player_ids => {"2" => "player_name1", "6" => "player_name4", "9" => "player_name9"}
输出:
{:player_ids => {"2" => "PRE_player_name1", "6" => "PRE_player_name4", "9" => "PRE_player_name9"}
This method is just changing the id for any player_id that is found. Reek hates it, but I can't find a way to refactor it in a meaningful way.
(1..9).each { |n|
n = n.to_s
self.player_ids[n] = self.site_id.clone << "_" << self.player_ids[n].clone if self.player_ids[n]
}
Do I just have to live with this duplication because the clone function doesn't allow me to:
player_id = self.player_ids[n]
player_id = self.site_id.clone << "_" << player_id.clone if player_id
Sample input:
{:player_ids => {"2" => "player_name1", "6" => "player_name4", "9" => "player_name9"}
output:
{:player_ids => {"2" => "PRE_player_name1", "6" => "PRE_player_name4", "9" => "PRE_player_name9"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的示例输入和输出,这里有两种可能的技术:
如果这不是您想要的,请编辑您问题的示例输入/输出并发表评论以澄清您的需求。
Here are two possible techniques, based on your sample input and output:
If this is not what you want, please edit your question's sample input/output and post a comment clarifying your needs.
仅当您在字符串上使用变异操作 (
<<
) 时才需要#clone
。使用字符串插值可以防止不必要的克隆,也使您的代码更加惯用。作为奖励,我删除了对
self
的不必要引用,并将 if 替换为 and-equals。#clone
is only required because you are using mutating operations (<<
) on the string. Using string interpolation prevents the unnecessary clone and also makes your code more idiomatic.As a bonus, I've removed your unnecessary references to
self
and replaced your if with an and-equals.