为什么这两种方法看起来相同?

时间:2013-09-09 04:49:57

标签: ruby syntax

我的方法exist­s_else有两个参数:basefallback。如果basenil,则返回fallback。如果不是nil,则返回base。致exist­s_else(true, false)的电话应该返回true

如果我使用标准的if语句,true会像我认为的那样返回:

def exist­s_else(bas­e, fallb­ack)
  unless base.­nil?
    base
  else
    fallb­ack
  end
end

a = true
exists_els­e( a, false­ )
# => true

如果我使用下面显示的内联实现,则返回false

def exist­s_else(base, fallback)
  base unles­s base.nil­? else fallback
end

a = true
exists_els­e( a, false­ )
# => false

为什么它会在内联实现中返回false

3 个答案:

答案 0 :(得分:6)

你的断言

base unles­s base.nil­? else fallback

应该等同于长格式unless语句不正确;事实上,你不能在帖子条件中使用else。 Ruby将代码解释为:

def exist­s_else(base, fallback)
  base unles­s base.nil­?
else fallback
end

如果您在IRB中输入此(或没有换行的版本,如您的问题),Ruby会发出以下警告:

warning: else without rescue is useless

也就是说,Ruby正试图将else解释为异常处理代码的一部分,如

def exists_else(base, fallback)
  base unless base.nil
rescue ArgumentError => e
  # code to handle ArgumentError here
else
  # code to handle other exceptions here
end

答案 1 :(得分:4)

如果您尝试在一行中执行此操作,则无法使用else语句。当需要else时,您必须使用扩展版本。

Ruby认为在这种情况下else与错误处理有关。您必须坚持使用最初的unless-end方法。

答案 2 :(得分:1)

我更喜欢这种语法来评估真/假检查:

condition(s) ? true_value : false_value

在您的情况下,它看起来像:

def exists_else(base, fallback)
  base.nil? ? fallback : base
end

a = true
puts exists_else(a, false)  # => true
相关问题