Ruby方法链接
发布时间:2020-12-17 03:38:16 所属栏目:百科 来源:网络整理
导读:我想在 Ruby中链接我自己的方法.而不是像这样编写ruby方法并使用它们: def percentage_to_i(percentage) percentage.chomp('%') percentage.to_iendpercentage = "75%"percentage_to_i(percentage)= 75 我想像这样使用它: percentage = "75%"percentage.pe
我想在
Ruby中链接我自己的方法.而不是像这样编写ruby方法并使用它们:
def percentage_to_i(percentage) percentage.chomp('%') percentage.to_i end percentage = "75%" percentage_to_i(percentage) => 75 我想像这样使用它: percentage = "75%" percentage.percentage_to_i => 75 我怎样才能做到这一点? 解决方法
您必须将该方法添加到String类:
class String def percentage_to_i self.chomp('%') self.to_i end end 有了这个,你可以得到你想要的输出: percentage = "75%" percentage.percentage_to_i # => 75 这有点无用,因为to_i已经为你做了: percentage = "75%" percentage.to_i # => 75 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |