ruby 我可以在 `elsif` 上使用 `else if` 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31859386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:45:52  来源:igfitidea点击:

Can I use `else if` over `elsif`?

ruby

提问by PrimRock

  1. Is it safe to use else ifover elsif?
  2. Is it better to use elsifbecause it follows Ruby's typing convention?
  3. Or is this a preference?
  1. 使用else ifover安全elsif吗?
  2. elsif因为它遵循 Ruby 的类型约定,所以使用更好吗?
  3. 或者这是一种偏好?

This is a piece of code taken from a book. I added extra endkeywords and swapped elsifkeywords with else ifs.

这是摘自一本书的一段代码。我添加了额外的end关键字并elsifelse ifs交换了关键字。

def describe(inhabitant)
  if inhabitant == "sophie"
    puts 'gender: female'
    puts 'height: 145'
  else if inhabitant == "paul"
    puts 'gender: male'
    puts 'height: 145'
  else if inhabitant == "dawn"
    puts 'gender: female'
    puts 'height: 170'
  else if inhabitant == "brian"
    puts 'gender: male'
    puts 'height: 180'
  else if 
    puts 'species: Trachemys scripta elegans'
    puts 'height: 6'
  end
  end 
  end   
  end
  end
end

This made me realize how ugly else ifis.

这让我意识到有多丑else if

回答by Yu Hao

You can use else ifand it's safe. However note that this means extra endkeywords are needed.

您可以使用else if,而且很安全。但是请注意,这意味着需要额外的end关键字。

if n == 1
  puts "foo"
elsif n == 2
  puts "bar"
end

is logically the same as:

在逻辑上是一样的:

if n == 1
  puts "foo"
else if n == 2
       puts "bar"
     end
end

or the equivalent:

或等价物:

if n == 1
  puts "foo"
else 
  if n == 2
    puts "bar"
  end
end

回答by onebree

TL;DR- Replacing elsifwith else ifis alright for a conditional with only 2 paths. Remember to close the second ifconditional created with else if. It is best practice to have as few levels of conditionals as you can, making for a less-complex method. So err on the side of caution and use elsif.

TL; DR-更换elsifelse if是不行了只有2路径的条件。请记住关闭if使用else if. 最好的做法是使用尽可能少的条件级别,从而使方法不那么复杂。因此,请谨慎使用elsif.

Depending on how you plan to write your method, else ifmaywork. It is not a good habit to get into, however.

根据您计划如何编写方法,else if可能会起作用。然而,这不是一个好习惯。

Take the following example. There are only 2 conditions. The second condition looks similar to elsif, but is interpreted as the second chunk of code:

以下面的例子为例。只有2个条件。第二个条件看起来类似于elsif,但被解释为第二个代码块:

# What you may want to write
if true
  puts 'true'
else if false
  puts 'false'
end

# How Ruby requires it
if true
  puts 'true'
else
  if false  # You may also do: puts 'false' if false
    puts 'false'
  end
end

The first block will search for another endto close the primary conditional. Take note, you can bypass the extra end with a single line ifstatement. (I only suggest this if the executed code can be written on a single line.)

第一个块将搜索另一个end来关闭主要条件。请注意,您可以使用单行if语句绕过额外的结尾。(如果执行的代码可以写在一行上,我只建议这样做。)

It is important to note that once you declare an else, you may have no other conditionals in the same tier as that else. Given the second example above, the second ifis nested under the else. If you were to call elseor elsifon the same tier as the initial else, the conditional will fail.

重要的是要注意,一旦声明了 an else,在同一层中就可能没有其他条件了else。鉴于上面的第二个示例,第二个if嵌套在else. 如果您要调用elseelsif与初始 相同的层else,则条件将失败。

Here is when you would not want to implement else if:

这是您不想实施的时候else if

def describe(inhabitant)
  if inhabitant == "sophie"
    puts 'gender: female'
    puts 'height: 145'
  elsif inhabitant == "paul"
    puts 'gender: male'
    puts 'height: 145'
  elsif inhabitant == "dawn"
    puts 'gender: female'
    puts 'height: 170'
  elsif inhabitant == "brian"
    puts 'gender: male'
    puts 'height: 180'
  else
    puts 'species: Trachemys scripta elegans'
    puts 'height: 6'
  end
end

Notice that neither of the elsifstatements can be "converted" to else ifin a clean way.

请注意,这两个elsif语句都不能else if以干净的方式“转换”为。

UPDATE: Thanks to Stefan, you can still use else if, leading to a very nested method.

更新:感谢Stefan,您仍然可以使用else if,从而导致非常嵌套的方法。

https://gist.github.com/sos4nt/a41b36d21f6eec5e0a42

https://gist.github.com/sos4nt/a41b36d21f6eec5e0a42

回答by spickermann

I would prefer elsifover else if. But that is just my opinion and technically there is no difference.

我宁愿elsif超过else if。但这只是我的意见,技术上没有区别。

But I would suggest to use a caseblock instead of multiple elsifyour example:

但我建议使用一个case块而不是多个elsif你的例子:

def describe(inhabitant)
  case inhabitant
  when "sophie"
    puts 'gender: female'
    puts 'height: 145'
  when "paul"
    puts 'gender: male'
    puts 'height: 145'
  when "dawn"
    puts 'gender: female'
    puts 'height: 170'
  when "brian"
    puts 'gender: male'
    puts 'height: 180'
  else
    puts 'species: Trachemys scripta elegans'
    puts 'height: 6'
  end

Or I would store that mapping in a hash:

或者我将该映射存储在哈希中:

PEOPLE = {
  'sophie' => { :gender => :female, :height => 145 },
  'paul'   => { :gender => :male,   :height => 145 },
  # ...
}

def describe(inhabitant)
  description = PEOPLE.fetch(
    inhabitant, { :species => 'Trachemys scripta elegans', :height => 6 }
  )

  puts "gender: #{description[:gender]}"    if description[:gender]
  puts "species: #{description[:species]}"  if description[:species]
  puts "height: #{description[:height]}"
end 

回答by Wand Maker

You should pick the option that results in better readable code.I give below an example of code where I tend to feel that use of else ifis more readable.

您应该选择导致代码可读性更好的选项。我在下面给出了一个代码示例,我倾向于认为使用 的else if更具可读性。

result = "Unknown"
error_code = 911

#  Version 1 - uses else if
if result == "Success"
    puts "Good job!"
else
    if error_code == "100"
        puts "No worries, we can still recover"
    else
        puts "Hopeless case!"
    end
end


#  Version 2 - uses elsif
if result == "Success"
    puts "Good job!"
elsif result != "Success" and error_code == "100"
    puts "No worries, we can still recover"
else
    puts "Hopeless case!"
end

My guess is this has to do something with Level of Abstraction. If all the conditions in the if-elsif-else-endare at same level, then it will be more readable. If they are at different levels, it may be beneficial to use fewelse ifin the code.

我的猜测是这与Level of Abstraction 有关系。如果 中的所有条件if-elsif-else-end都在同一级别,那么它会更具可读性。如果它们处于不同的级别,则else if在代码中少用一些可能会有好处。