[英]How can I cleanly define “antonym” or “opposite” methods in Ruby / Rails?
I'm pretty often defining methods and their antonyms in the code I'm writing, as in: 我经常在我编写的代码中定义方法及其反义词,例如:
def happy?
@happiness > 3
end
def sad?
!happy?
end
Which is fine, but I'm a little surprised that Ruby or ActiveSupport doesn't give me something like: 很好,但是我对Ruby或ActiveSupport没有给我以下信息感到惊讶:
def happy?
@happiness > 3
end
alias_opposite :sad? :happy?
Or am I just looking in the wrong place? 还是我只是在错误的地方看?
There is no such method in popular libraries, but there is how this could be implemented 流行的库中没有这种方法,但是可以通过这种方法实现
class Module
def alias_opposite(a, b)
define_method(a) { !self.send(b) }
end
end
Usage 用法
class A < Struct.new(:happiness)
def happy?
happiness > 3
end
alias_opposite :sad?, :happy?
end
p A.new(1).sad? # => true
p A.new(5).sad? # => false
I suspect this pattern is not as common in ruby because the unless
keyword often does the trick: 我怀疑这种模式在红宝石中并不常见,因为
unless
关键字通常可以解决问题:
# ...
clap_your_hands if happy?
stomp_your_feet unless happy?
# ...
Of course, its simple to roll your own: 当然,滚动自己的方法很简单:
module Antonymator
def define_antonym(as, of)
define_method(as.to_sym) do |*args|
return !(send(of.to_sym, *args))
end
end
end
# Usage Example
class AreThey
extend Antonymator
define_antonym :uneql?, :eql?
define_antonym :nonconsecutive?, :consecutive?
def eql?(a, b)
a == b
end
def consecutive?(a, b)
a.next == b
end
end
are_they = AreThey.new
puts are_they.uneql? 1, 2 # true
puts are_they.nonconsecutive? 1, 2 # false
If your methods return a Boolean, you can always include the positive method in the negative method. 如果您的方法返回布尔值,则可以始终在否定方法中包括肯定方法。
def drinking_age?(age)
age > @restricted_age
end
def not_drinking_age?(age)
!drinking_age?(age)
end
@restricted_age = 20
Hope that helps. 希望能有所帮助。
I guess it depends on what 'opposite' means in the context. 我想这取决于上下文中“相反”的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.