在C#中有一个null-coalescing运算符(写为??),允许在赋值期间进行简单(短)空检查:
string s = null;
var other = s ?? "some default value";
Run Code Online (Sandbox Code Playgroud)
是否有python等价物?
我知道我能做到:
s = None
other = s if s else "some default value"
Run Code Online (Sandbox Code Playgroud)
但是有更短的方式(我不需要重复s)?
我想避免迭代nil数组.
我的坏解决方案:
if nil!=myArr
myArr.each { |item|
p item;
}
end
Run Code Online (Sandbox Code Playgroud) 我经常发现自己这样做:
do_something if x && x == y
Run Code Online (Sandbox Code Playgroud)
在其他作品中,如果x不是零,则执行某些操作,并且其值为y.
如果我可以做这样的事情,那将是很好的:
do_something if x &&== y
Run Code Online (Sandbox Code Playgroud)
是否有运营商这样做?
回复评论:
x == y- 问题在于,如果y已知值,它只测试存在(不是nil).如果y是本身nil则检查失败.所以你最终可能会这样做:
y && x == y
Run Code Online (Sandbox Code Playgroud)
x ||= y-这将分配的值y来x如果x是零.那不是我想要的.x &&= y由于同样的原因,它不起作用 - 它将值更改x为yif if xexists.
示例:在我当前的场景中,我想检查用户是否已将与其关联的令牌传递给控制器,但我还想确保已分配令牌.就像是:
do_something if user.token && user.token == params[:token]
Run Code Online (Sandbox Code Playgroud) 下面是Ruby中命名参数的示例,但是&符号有什么作用?
def set_tools(foo:, bar:, baz:)
@instance_variable = baz&.stuff
Run Code Online (Sandbox Code Playgroud) 我有一个名为的脚本import.rb,它将从 url 导入 json 内容到 jekyll 中的草稿目录。下面是我的代码。
require 'fileutils'
require 'json'
require 'open-uri'
# Load JSON data from source
# (Assuming the data source is a json file on your file system)
data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec'))
# Proceed to create post files if the value array is not empty
array = data["user"]
if array && !array.empty?
# create the `_drafts` directory if it doesn't exist already
drafts_dir = File.expand_path('./_drafts', __dir__)
FileUtils.mkdir_p(drafts_dir) unless Dir.exist?(drafts_dir)
# iterate through the array and …Run Code Online (Sandbox Code Playgroud) irb(main):007:0> %w[1 2 3 4 5]&.each { |a| puts a }
1
2
3
4
5
=> ["1", "2", "3", "4", "5"]
irb(main):008:0> %w[1 2 3 4 5].each { |a| puts a }
1
2
3
4
5
=> ["1", "2", "3", "4", "5"]
Run Code Online (Sandbox Code Playgroud)
双方&.each并.each似乎给了相同的结果
ruby-doc似乎没有关于此功能的任何内容
两者有什么区别?