2012-04-28 76 views
4

我想在Ruby中链接自己的方法。而不是编写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 

我怎样才能做到这一点?

+0

为什么不做一个'Percent'类? – 2012-04-28 02:27:50

回答

7

你的方法添加到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 
+0

哈哈我最终这样做,并回来写我自己的答案。等待接受你的。谢谢。 – Dru 2012-04-28 02:30:11

+0

谢谢,问题更多的是关于链接,但我不知道我可以单独使用'to_i'做同样的事情。 – Dru 2012-04-28 23:43:15

+0

我将该方法添加到String类(如您的答案中),但在模型文件('app/models/content.rb')中,在该模型的类定义的“end”语句之后。我认为这样做被称为“mixin”。 – user664833 2012-09-18 19:21:03

0

单例方法

def percentage.percentage_to_i 
    self.chomp('%') 
    self.to_i 
end 

创建自己的类

class Percent 
    def initialize(value) 
    @value = value 
    end 

    def to_i 
    @value.chomp('%') 
    @value.to_i 
    end 

    def to_s 
    "#{@value}%" 
    end 
end 
+0

有趣的是,这会比延长课程更有利吗?我试图找出一个与Singleton方法有关的额外工作的用例吗? – Dru 2012-04-28 02:32:43

+1

@Dru Singleton方法在实例上是一次性事物时非常有用。当我需要将对象变形为API以用于库函数时,我已经使用过它们,但它们并不经常需要。 – 2012-04-28 02:38:30

+0

@AndrewMarshall谢谢 – Dru 2012-04-28 02:39:40

1

这不是完全清楚你想要什么。

如果您希望能够将字符串转换to_i的一个实例,然后就叫to_i:

"75%".to_i => 75 

如果你想让它有一些特殊的行为,那么猴子修补String类:

class String 
    def percentage_to_i 
     self.to_i # or whatever you want 
    end 
end 

如果您确实想要链接方法,那么您通常要返回相同类的修改后的实例。

class String 
    def half 
     (self.to_f/2).to_s 
    end 
end 

s = "100" 
s.half.half => "25"