Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

デフォルト式の制約の説明が実態と合っていない #2033

Open
urimaro opened this issue Nov 17, 2019 · 1 comment
Open

デフォルト式の制約の説明が実態と合っていない #2033

urimaro opened this issue Nov 17, 2019 · 1 comment

Comments

@urimaro
Copy link
Contributor

urimaro commented Nov 17, 2019

メソッド定義 にて、デフォルト式について以下のように説明されています。

ただし実引数との対応を取るため、i番目の引数にデフォルト値を指定したならば、 i+1番目以降でも全てデフォルト値を指定するか、可変長引数を利用しなければなりません(詳細は後述)。

Ruby2.6.5にて、以下のコードを試してみたところ、期待通りに動作しました。

  1. 左端の「a」のみ省略可能

    def func(a=0, b, c)
      puts a + b + c
    end
    
    func(1, 2)     #=> 3
    func(1, 2, 3)  #=> 6
    
  2. 左端の「a」、途中の「b」が省略可能

    def func(a=0, b=1, c)
      puts a + b + c
    end
    
    func(2)        #=> 3
    func(1, 2, 3)  #=> 6
    
  3. 途中の「b」のみ省略可能

    def func(a, b=1, c)
      puts a + b + c
    end
    
    func(0, 2)     #=> 3
    func(1, 2, 3)  #=> 6
    

以下のコードはエラーになったことから「デフォルト式はまとめて指定しなければいけない」のではないかと思いました。

  1. 左端の「a」、右端の「c」が省略可能

    def func(a=0, b, c=2)
      puts a + b + c
    end
    
    func(1)        #=> syntax error
    func(1, 2, 3)
    

なお、英語版のリファレンスマニュアルの Default Values では以下のように説明がされていました。

The default value does not need to appear first, but arguments with defaults must be grouped together.

@pocke
Copy link
Member

pocke commented Nov 17, 2019

この説明の少し下のほうに

Ruby 1.9 以降では可変長引数よりも後にまだ通常の引数を置くことができます。

とあるので、Ruby 1.8までの仕様を引きずった書き方になっていると思いますね。

1.8のことを考慮せず、1.9からの引数の定義にのっとった形に書き換えてしまうのが良いかなと思います。英語版のほうを元にするのも良さそうですね

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants