新手问题 CoffeeScript 里 `?=` 这个运算符在 Ruby 里有对应的语法吗?

layerssss · August 31, 2014 · Last by creeek replied at September 03, 2014 · 1754 hits

#1 楼 @ShiningRay||= ,当运算符左边的值为 false 时,它和 ?= 的行为不一样。

#2 楼 @layerssss 那说明 JS 和 Ruby 对于 undefined 的概念是不一样的

#3 楼 @ShiningRay @layerssss 楼主期待的是能可以得到以下结果的运算符?

001 > a = nil
 => nil
002 > a = a.nil? ? 2 : a
 => 2
003 > a = false
 => false
004 > a = a.nil? ? 2 : a
 => false

#3 楼 @ShiningRay Javascript 里面 null 和 undefined 还是不一样的

#5 楼 @creeek ruby 里面没 undefined 一说

#6 楼 @ShiningRay 对,Ruby 中没有 undefined Ruby 中不记得有 @layerssss 需要的方法,求科普~

#7 楼 @creeek 其实我主要是要处理参数默认值,options.option1 ?= true 在 coffee 里就用 ?= 而非 ||=,否则 false 和 '' 处理不了,ruby 里如果没有对应方法就用 options.merge 好了。

#8 楼 @layerssss option1 为 false 时进行 merge 的话,option1 会不会被强制覆盖成 true?

#9 楼 @creeek 你自己试一下即知

#10 楼 @layerssss 试过了,会覆盖

是这样用的

[1] pry(main)> h = { a: false }
=> {:a=>false}
[2] pry(main)> h = { a: true, b: 2}.merge h
=> {:a=>false, :b=>2}

#12 楼 @layerssss 有点较真,不过实际情况中不一定存在这种情况

[1] pry(main)> h = { a: false, b: nil }
=> {:a=>false, :b=>nil}
[2] pry(main)> h = { a: true, b: 2 }.merge h
=> {:a=>false, :b=>nil}
You need to Sign in before reply, if you don't have an account, please Sign up first.