gpt4 book ai didi

ruby - `do` ... `end` 语句在没有 block 参数的情况下如何工作?

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

例如,在 Rails gemfile 中:

group :development, :test do
gem 'rspec-rails', '~> 2.0'
end

do ... end 语句发生了什么?和 rspec:

describe "Foo" do
context "bar" do
expect...
end
end

do ... end 是否创建了一个 block ,其间的信息正在别处使用?如果不设置 block 参数,这是如何工作的?

最佳答案

这叫做领域特定语言

A Domain-Specific Language, or DSL, is “a programming language of limited expressiveness focused on a particular domain”. It makes tasks in its domain easier by removing extraneous code for a particular task and allowing you to focus on the specific task at hand. It also helps other people read the code, because the purpose of the code is so clear.

基本上是这样

group :development, :test do
gem 'rspec-rails', '~> 2.0'
end

只是使用参数 :development, :test 和 block gem 'rspec-rails', '~> 2.0 调用方法 group 'Which is defined in this way in Bundler DSL :

def group(*args, &blk)
...
end

第二个例子也一样。

DSL defines methods to group examples, most notably describe, and exposes them as class methods of RSpec.

.describe is being implemented in this way :

def describe(doc_string, *metadata_keys, metadata = {}, &example_implementation)
...
end

您可以阅读有关使用 Ruby 编写领域特定语言的更多信息 in this thoughtbot.com article

关于ruby - `do` ... `end` 语句在没有 block 参数的情况下如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378601/

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