Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Range类的文本构造函数的命名构造函数等价物是什么?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails Range类的文本构造函数的命名构造函数等价物是什么?

Ruby on rails Range类的文本构造函数的命名构造函数等价物是什么?,ruby-on-rails,ruby,Ruby On Rails,Ruby,对rails有些陌生。我正在完成Michael Hartl的learn rails教程中4.4.1的练习,对于类范围的命名构造函数是什么,我有点不清楚 当我在控制台中键入文本构造函数时,它将返回适当的值 (1..10) =>1..10 但是当我尝试命名构造函数时 Range.new(1..10) 我收到一个错误 ArgumentError: wrong number of arguments (given 1, expected 2..3) from (irb):104:in

对rails有些陌生。我正在完成Michael Hartl的learn rails教程中4.4.1的练习,对于类范围的命名构造函数是什么,我有点不清楚

当我在控制台中键入文本构造函数时,它将返回适当的值

(1..10)
=>1..10
但是当我尝试命名构造函数时

Range.new(1..10)
我收到一个错误

ArgumentError: wrong number of arguments (given 1, expected 2..3)
    from (irb):104:in `initialize'
    from (irb):104:in `new'
我尝试过添加许多类型的额外参数,例如

Range.new(1)..Range.new(10)
Range.new(1)..(10)
etc..
但我总是遇到一个论点错误

ArgumentError:参数数目错误(给定1,应为2..3)

应提示您至少需要2个参数:

Range.new(1,10)
第三个参数用于指定是否排除范围的最后一个元素:

Range.new(1,10,false).to_a
# equivalent to (1..10)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Range.new(1,10,true).to_a
# equivalent to (1...10)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]

你的代码 这仍然只有一个参数:已经初始化的范围

Range.new(1)..Range.new(10)
这是一种
a..b
语法,因此它尝试初始化
a
b
之间的范围。什么是
a
<代码>范围。新建(1),未定义,因为它只有1个参数。无论如何,您不能在两个范围之间创建一个范围:

Range.new(1,2)..Range.new(4,5)
#=> ArgumentError: bad value for range

Range.new(1)..(10)

和以前一样的问题。只有一个参数用于
范围。新建
,这将是一个介于范围和整数之间的范围

您可以使用
ri
命令阅读文档

ri Range.new
哪张照片

= Range.new

(from ruby site)
------------------------------------------------------------------------------
  Range.new(begin, end, exclude_end=false)    -> rng

------------------------------------------------------------------------------

Constructs a range using the given begin and end. If the exclude_end parameter
is omitted or is false, the rng will include the end object; otherwise, it
will be excluded.

注意,
ri
在终端命令行和
pry
repl中都起作用。

根据时间戳,你比我快了3秒…:)你不必删除你的答案,但我会在下次发布类似答案后立即删除!我懂了!该文档有点混乱,因为它使用Xs.new(3)…Xs.new(6)构建了一个新的范围,但现在有了意义。谢谢你!谢谢你的帮助。
= Range.new

(from ruby site)
------------------------------------------------------------------------------
  Range.new(begin, end, exclude_end=false)    -> rng

------------------------------------------------------------------------------

Constructs a range using the given begin and end. If the exclude_end parameter
is omitted or is false, the rng will include the end object; otherwise, it
will be excluded.