gpt4 book ai didi

ruby - 如何在 Ruby 中使用大括号扩展?

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:28 26 4
gpt4 key购买 nike

假设我想要以下规范:

it { should allow_value("git://host.xz/path/to/repo.git/").for(:url) }
it { should allow_value("git://user@host.xz/path/to/repo.git/").for(:url) }
it { should allow_value("git://host.xz:123/path/to/repo.git/").for(:url) }
it { should allow_value("git://user@host.xz:123/path/to/repo.git/").for(:url) }
...

如果我能写的话会更简单更紧凑:

"git://{user@,}host.xz{:123,}/path/to/repo.git".expand.each do |p|
it { should allow_value(p).for(:url) }
end

或者更好:

"{git,ssh,http,https,rsync}://[user@]host.xz[:123]/path/to/repo.git[/]".expand.each do |p|
it { should allow_value(p).for(:url) }
end

在 Ruby 中有哪些方法可以实现这一点?

编辑我尝试的第一件事是 bracecomp , 但我无法让它在 1.9.3 中工作。

[1] pry(main)> require 'bracecomp'
[2] pry(main)> 'server-{a,b}-{07..10}'.expand
TypeError: scan() yielded Symbol (must be Array[2])
from bracecomp.y:66:in `scan'

最佳答案

怎么样

%w[git ssh http https rsync].product(['user@', nil], [':123', nil]).each do |protocol, user, port|
it { should allow_value("#{protocol}://#{user}host.xz#{port}/path/to/repo.git").for(:url) }
end

不依赖于外部库,每个 Ruby 开发人员都可以理解。

尽管我认为这确实需要规范助手或自定义匹配器。

关于ruby - 如何在 Ruby 中使用大括号扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com