bou*_*uby 5 ruby case andand conditional-statements or-operator
我只是尝试运行一些看起来像这样的代码
def get_proj4(srid, type=nil)
type.downcase! if type
case type
when nil || "epsg"
open("http://spatialreference.org/ref/epsg/#{srid}/proj4/").read
when "esri"
open("http://spatialreference.org/ref/esri/#{srid}/proj4/").read
end
end
Run Code Online (Sandbox Code Playgroud)
而且它运行不正常,每次都返回nil。将 括nil || "epsg"在括号中也不起作用
事实证明 ruby 不允许我||在此使用运算符
现在我假设 ruby 采用 case/when 方法并最终将其分解为一组看起来像这样的条件
x = type
if x == (nil || "epsg")
y = ...runs code...
elsif x == "esri"
y = ...
end
x = nil
y
Run Code Online (Sandbox Code Playgroud)
但显然事实并非如此。这里发生了什么?
谢谢
该表达式首先被求值,因此when nil || "espg"等于when "espg"1 - 它永远不会匹配nil。
要匹配“非此即彼”,请用逗号分隔选项:
case type
when nil, "espg" ..
when "esri" ..
Run Code Online (Sandbox Code Playgroud)
或者,也许可以标准化该值:
case (type || "espg")
when "espg" ..
when "esri" ..
Run Code Online (Sandbox Code Playgroud)
或者使用类似于 if-else 的其他形式:
case
when type.nil? || type == "espg" ..
when type == "esri" ..
Run Code Online (Sandbox Code Playgroud)
或者所有东西的某种组合:)
1if这也是该例子值得怀疑的原因。大概应该这样写:
if type.nil? || type == "espg"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
931 次 |
| 最近记录: |