From 3e4ce193432446c2a0610face701c2375ee8f0bd Mon Sep 17 00:00:00 2001 From: Fumiya Shibusawa Date: Tue, 7 Jan 2020 15:27:45 +0900 Subject: [PATCH 0001/1292] feat: add ja translation for community guideline page --- ja/conduct/index.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 ja/conduct/index.md diff --git a/ja/conduct/index.md b/ja/conduct/index.md new file mode 100644 index 0000000000..05de7bfc5b --- /dev/null +++ b/ja/conduct/index.md @@ -0,0 +1,15 @@ +--- +layout: page +title: "Rubyコミュニティの行動規範ガイドライン" +lang: ja +--- + +Ruby開発者のコミュニティにおける安全かつ生産的なコラボレーションのため、以下の行動規範ガイドラインを用意しています。なお、これらはPostgreSQLの行動規範のドラフトを参考にしています。Rubyに関係するコミュニティ(カンファレンスなど)などで行動規範をつくる際にここから目的に沿うものを取っていただいて構いません。 +{: .summary} + +このドキュメントは、Rubyコミュニティに貢献したいと思うすべての人々にとって安全で生産的かつ協力的で互いに敬意を払える場所を提供するためのものです。コミュニティでコミュニケーションをする場(メーリングリスト、パッチの提出、commitのコメントなど)などすべてで適用されます。 + + * 参加者は、自身とは異なる意見、考えにも寛容な態度を示します。 + * 参加者は個人に対する攻撃や誹謗中傷などを示す発言・行動がないことを保証します。 + * 他の参加者の言葉や行動を解釈する際、それらが常に善意に基づくものだという前提に立ちます。 + * 合理的に考えてそれがハラスメントだとみなされる振る舞いは許容しません。 From 8ae349b56f7387677ab8b9c5183bebf4d02ea2cd Mon Sep 17 00:00:00 2001 From: hachi8833 Date: Wed, 22 Jan 2020 12:35:17 +0900 Subject: [PATCH 0002/1292] Add en doc --- ...ional-and-keyword-arguments-in-ruby-3-0.md | 355 ++++++++++++++++++ 1 file changed, 355 insertions(+) create mode 100644 ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md diff --git a/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md new file mode 100644 index 0000000000..44cd874cc1 --- /dev/null +++ b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md @@ -0,0 +1,355 @@ +--- +layout: news_post +title: "Separation of positional and keyword arguments in Ruby 3.0" +author: "mame" +translator: +date: 2019-12-12 12:00:00 +0000 +lang: en +--- + +This article explains the planned incompatibility of keyword arguments in Ruby 3.0 + +## tl;dr + +In Ruby 3.0, positional arguments and keyword arguments will be separated. Ruby 2.7 will warn for behaviors that will change in Ruby 3.0. If you see the following warnings, you need to update your code: + +* `Using the last argument as keyword parameters is deprecated`, or +* `Passing the keyword argument as the last hash parameter is deprecated`, or +* `Splitting the last argument into positional and keyword parameters is deprecated` + +In most cases, you can avoid the incompatibility by adding the _double splat_ operator. It explicitly specifies passing keyword arguments instead of a `Hash` object. Likewise, you may add braces `{}` to explicitly pass a `Hash` object, instead of keyword arguments. Read the section "Typical cases" below for more details. + +In Ruby 3, a method delegating all arguments must explicitly delegate keyword arguments in addition to positional arguments. If you want to keep the delegation behavior found in Ruby 2.7 and earlier, use `ruby2_keywords`. See the "Handling argument delegation" section below for more details. + +## Typical cases + +Here is the most typical case. You can use double splat operator (`**`) to pass keywords instead of a Hash. + +{% highlight ruby %} +# This method accepts only a keyword argument +def foo(k: 1) + p k +end + +h = { k: 42 } + +# This method call passes a positional Hash argument +# In Ruby 2.7: The Hash is automatically converted to a keyword argument +# In Ruby 3.0: This call raises an ArgumentError +foo(h) + # => demo.rb:11: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call + # demo.rb:2: warning: The called method `foo' is defined here + # 42 + +# If you want to keep the behavior in Ruby 3.0, use double splat +foo(**h) #=> 42 +{% endhighlight %} + +Here is another case. You can use braces (`{}`) to pass a Hash instead of keywords explicitly. + +{% highlight ruby %} +# This method accepts one positional argument and a keyword rest argument +def bar(h, **kwargs) + p h +end + +# This call passes only a keyword argument and no positional arguments +# In Ruby 2.7: The keyword is converted to a positional Hash argument +# In Ruby 3.0: This call raises an ArgumentError +bar(k: 42) + # => demo2.rb:9: warning: Passing the keyword argument as the last hash parameter is deprecated + # demo2.rb:2: warning: The called method `bar' is defined here + # {:k=>42} + +# If you want to keep the behavior in Ruby 3.0, write braces to make it an +# explicit Hash +bar({ k: 42 }) # => {:k=>42} +{% endhighlight %} + +## What is deprecated? + +In Ruby 2, keyword arguments can be treated as the last positional Hash argument and a last positional Hash argument can be treated as keyword arguments. + +Because the automatic conversion is sometimes too complex and troublesome as described in the final section. So it's now deprecated in Ruby 2.7 and will be removed in Ruby 3. In other words, keyword arguments will be completely separated from positional one in Ruby 3. So when you want to pass keyword arguments, you should always use `foo(k: expr)` or `foo(**expr)`. If you want to accept keyword arguments, in principle you should always use `def foo(k: default)` or `def foo(k:)` or `def foo(**kwargs)`. + +Note that Ruby 3.0 doesn't behave differently when calling a method which doesn't accept keyword arguments with keyword arguments. For instance, the following case is not going to be deprecated and will keep working in Ruby 3.0. The keyword arguments are still treated as a positional Hash argument. + +{% highlight ruby %} +def foo(kwargs = {}) + kwargs +end + +foo(k: 1) #=> {:k=>1} +{% endhighlight %} + +This is because this style is used very frequently, and there is no ambiguity in how the argument should be treated. Prohibiting this conversion would result in additional incompatibility for little benefit. + +However, this style is not recommended in new code, unless you are often passing a Hash as a positional argument, and are also using keyword arguments. Otherwise, use double splat: + +{% highlight ruby %} +def foo(**kwargs) + kwargs +end + +foo(k: 1) #=> {:k=>1} +{% endhighlight %} + +## Will my code break on Ruby 2.7? + +A short answer is "maybe not". + +The changes in Ruby 2.7 are designed as a migration path towards 3.0. While in principle, Ruby 2.7 only warns against behaviors that will change in Ruby 3, it includes some incompatible changes we consider to be minor. See the "Other minor changes" section for details. + +Except for the warnings and minor changes, Ruby 2.7 attempts to keep the compatibility with Ruby 2.6. So, your code will probably work on Ruby 2.7, though it may emit warnings. And by running it on Ruby 2.7, you can check if your code is ready for Ruby 3.0. + +If you want to disable the deprecation warnings, please use a command-line argument `-W:no-deprecated` or add `Warning[:deprecated] = false` to your code. + +## Handling argument delegation + +### Ruby 2.6 or prior + +In Ruby 2, you can write a delegation method by accepting a `*rest` argument and a `&block` argument, and passing the two to the target method. In this behavior, the keyword arguments are also implicitly handled by the automatic conversion between positional and keyword arguments. + +{% highlight ruby %} +def foo(*args, &block) + target(*args, &block) +end +{% endhighlight %} + +### Ruby 3 + +You need to explicitly delegate keyword arguments. + +{% highlight ruby %} +def foo(*args, **kwargs, &block) + target(*args, **kwargs, &block) +end +{% endhighlight %} + +Alternatively, if you do not need compatibility with Ruby 2.6 or prior and you don't alter any arguments, you can use the new delegation syntax (`...`) that is introduced in Ruby 2.7. + +{% highlight ruby %} +def foo(...) + target(...) +end +{% endhighlight %} + +### Ruby 2.7 + +In short: use `Module#ruby2_keywords` and delegate `*args, &block`. + +{% highlight ruby %} +ruby2_keywords def foo(*args, &block) + target(*args, &block) +end +{% endhighlight %} + +`ruby2_keywords` accepts keyword arguments as the last Hash argument, and passes it as keyword arguments when calling the other method. + +In fact, Ruby 2.7 allows the new style of delegation in many cases. However, there is a known corner case. See the next section. + +### A compatible delegation that works on Ruby 2.6, 2.7 and Ruby 3 + +In short: use `Module#ruby2_keywords` again. + +{% highlight ruby %} +ruby2_keywords def foo(*args, &block) + target(*args, &block) +end +{% endhighlight %} + +Unfortunately, we need to use the old-style delegation (i.e., no `**kwargs`) because Ruby 2.6 or prior does not handle the new delegation style correctly. This is one of the reasons of the keyword argument separation; the details are described in the final section. And `ruby2_keywords` allows you to run the old style even in Ruby 2.7 and 3.0. As there is no `ruby2_keywords` defined in 2.6 or prior, please use the [ruby2_keywords gem](https://rubygems.org/gems/ruby2_keywords) or define it yourself: + +{% highlight ruby %} +def ruby2_keywords(*) +end if RUBY_VERSION < "2.7" +{% endhighlight %} + +--- + +If your code doesn't have to run on Ruby 2.6 or older, you may try the new style in Ruby 2.7. In almost all cases, it works. Note that, however, there are unfortunate corner cases as follows: + +{% highlight ruby %} +def target(*args) + p args +end + +def foo(*args, **kwargs, &block) + target(*args, **kwargs, &block) +end + +foo({}) #=> Ruby 2.7: [] ({} is dropped) +foo({}, **{}) #=> Ruby 2.7: [{}] (You can pass {} by explicitly passing "no" keywords) +{% endhighlight %} + +An empty Hash argument is automatically converted and absorbed into `**kwargs`, and the delegation call removes the empty keyword hash, so no argument is passed to `target`. As far as we know, this is the only corner case. + +As noted in the last line, you can work around this issue by using `**{}`. + +If you really worry about the portability, use `ruby2_keywords`. (Acknowledge that Ruby 2.6 or before themselves have tons of corner cases in keyword arguments. :-) +`ruby2_keywords` might be removed in the future after Ruby 2.6 reaches end-of-life. At that point, we recommend to explicitly delegate keyword arguments (see Ruby 3 code above). + +## Other minor changes + +There are three minor changes about keyword arguments in Ruby 2.7. + +### 1. Non-Symbol keys are allowed in keyword arguments + +In Ruby 2.6 or before, only Symbol keys were allowed in keyword arguments. In Ruby 2.7, keyword arguments can use non-Symbol keys. + +{% highlight ruby %} +def foo(**kwargs) + kwargs +end +foo("key" => 42) + #=> Ruby 2.6 or before: ArgumentError: wrong number of arguments + #=> Ruby 2.7 or later: {"key"=>42} +{% endhighlight %} + +If a method accepts both optional and keyword arguments, the Hash object that has both Symbol keys and non-Symbol keys was split in two in Ruby 2.6. In Ruby 2.7, both are accepted as keywords because non-Symbol keys are allowed. + +{% highlight ruby %} +def bar(x=1, **kwargs) + p [x, kwargs] +end + +bar("key" => 42, :sym => 43) + #=> Ruby 2.6: [{"key"=>42}, {:sym=>43}] + #=> Ruby 2.7: [1, {"key"=>42, :sym=>43}] + +# Use braces to keep the behavior +bar({"key" => 42}, :sym => 43) + #=> Ruby 2.6 and 2.7: [{"key"=>42}, {:sym=>43}] +{% endhighlight %} + +Ruby 2.7 still splits hashes with a warning if passing a Hash or keyword arguments with both Symbol and non-Symbol keys to a method that accepts explicit keywords but no keyword rest argument (`**kwargs`). This behavior will be removed in Ruby 3, and an `ArgumentError` will be raised. + +{% highlight ruby %} +def bar(x=1, sym: nil) + p [x, sym] +end + +bar("key" => 42, :sym => 43) +# Ruby 2.6 and 2.7: => [{"key"=>42}, 43] +# Ruby 2.7: warning: Splitting the last argument into positional and keyword parameters is deprecated +# warning: The called method `bar' is defined here +# Ruby 3.0: ArgumentError +{% endhighlight %} + +### 2. Double splat with an empty hash (`**{}`) passes no arguments + +In Ruby 2.6 or before, passing `**empty_hash` passes an empty Hash as a positional argument. In Ruby 2.7 or later, it passes no arguments. + +{% highlight ruby %} +def foo(*args) + args +end + +empty_hash = {} +foo(**empty_hash) + #=> Ruby 2.6 or before: [{}] + #=> Ruby 2.7 or later: [] +{% endhighlight %} + +Note that `foo(**{})` passes nothing in both Ruby 2.6 and 2.7. In Ruby 2.6 and before, `**{}` is removed by the parser, and in Ruby 2.7 and above, it is treated the same as `**empty_hash`, allowing for an easy way to pass no keyword arguments to a method. + +In Ruby 2.7, when calling a method with an insufficient number of required positional arguments, `foo(**empty_hash)` passes an empty hash with a warning emitted, for compatibility with Ruby 2.6. This behavior will be removed in 3.0. + +{% highlight ruby %} +def foo(x) + x +end + +empty_hash = {} +foo(**empty_hash) + #=> Ruby 2.6 or before: {} + #=> Ruby 2.7: warning: Passing the keyword argument as the last hash parameter is deprecated + # warning: The called method `foo' is defined here + #=> Ruby 3.0: ArgumentError: wrong number of arguments +{% endhighlight %} + +### 3. The no-keyword-arguments syntax (`**nil`) is introduced + +You can use `**nil` in a method definition to explicitly mark the method accepts no keyword arguments. Calling such methods with keyword arguments will result in an `ArgumentError`. (This is actually a new feature, not an incompatibility) + +{% highlight ruby %} +def foo(*args, **nil) +end + +foo(k: 1) + #=> Ruby 2.7 or later: no keywords accepted (ArgumentError) +{% endhighlight %} + +This is useful to make it explicit that the method does not accept keyword arguments. Otherwise, the keywords are absorbed in the rest argument in the above example. If you extend a method to accept keyword arguments, the method may have incompatibility as follows: + +{% highlight ruby %} +# If a method accepts rest argument and no `**nil` +def foo(*args) + p args +end + +# Passing keywords are converted to a Hash object (even in Ruby 3.0) +foo(k: 1) #=> [{:k=>1}] + +# If the method is extended to accept a keyword +def foo(*args, mode: false) + p args +end + +# The existing call may break +foo(k: 1) #=> ArgumentError: unknown keyword k +{% endhighlight %} + +## Why we're deprecating the automatic conversion + +The automatic conversion initially appeared to be a good idea, and worked well in many cases. However, it had too many corner cases, and we have received many bug reports about the behavior. + +Automatic conversion does not work well when a method accepts optional positional arguments and keyword arguments. Some people expect the last Hash object to be treated as a positional argument, and others expect it to be converted to keyword arguments. + +Here is one of the most confusing cases: + +{% highlight ruby %} +def foo(x, **kwargs) + p [x, kwargs] +end + +def bar(x=1, **kwargs) + p [x, kwargs] +end + +foo({}) => [{}, {}] +bar({}) => [1, {}] + +bar({}, **{}) => expected: [{}, {}], actual: [1, {}] +{% endhighlight %} + +In Ruby 2, `foo({})` passes an empty hash as a normal argument (i.e., `{}` is assigned to `x`), while `bar({})` passes a keyword argument (i.e, `{}` is assigned to `kwargs`). So `any_method({})` is very ambiguous. + +You may think of `bar({}, **{})` to pass the empty hash to `x` explicitly. Surprisingly, it does not work as you expected; it still prints `[1, {}]` in Ruby 2.6. This is because `**{}` is ignored by the parser in Ruby 2.6, and the first argument `{}` is automatically converted to keywords (`**kwargs`). In this case, you need to call `bar({}, {})`, which is very weird. + +The same issues also apply to methods that accept rest and keyword arguments. This makes explicit delegation of keyword arguments not work. + +{% highlight ruby %} +def target(*args) + p args +end + +def foo(*args, **kwargs, &block) + target(*args, **kwargs, &block) +end + +foo() #=> Ruby 2.6 or before: [{}] + #=> Ruby 2.7 or later: [] +{% endhighlight %} + +`foo()` passes no arguments, but `target` receives an empty hash argument in Ruby 2.6. This is because the method `foo` delegates keywords (`**kwargs`) explicitly. When `foo()` is called, `args` is an empty Array, `kwargs` is an empty Hash, and `block` is `nil`. And then `target(*args, **kwargs, &block)` passes an empty Hash as an argument because `**kwargs` is automatically converted to a positional Hash argument. + +The automatic conversion not only confuses people but also makes the method less extensible. See [[Feature #14183]](https://bugs.ruby-lang.org/issues/14183) for more details about the reasons for the change in behavior, and why certain implementation choices were made. + +## Acknowledgment + +This article was kindly reviewed (or even co-authored) by Jeremy Evans and Benoit Daloze. + +## History + +* Updated 2019-12-25: In 2.7.0-rc2, the warning message was slightly changed, and an API to suppress the warnings was added. From a883bdda941814ffb08f6c1156453f8859655863 Mon Sep 17 00:00:00 2001 From: hachi8833 Date: Wed, 22 Jan 2020 12:35:47 +0900 Subject: [PATCH 0003/1292] Translate "Separation of positional and keyword arguments in Ruby 3.0" --- ...ional-and-keyword-arguments-in-ruby-3-0.md | 195 +++++++++--------- 1 file changed, 99 insertions(+), 96 deletions(-) diff --git a/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md index 44cd874cc1..5e80e231d5 100644 --- a/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md +++ b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md @@ -2,77 +2,81 @@ layout: news_post title: "Separation of positional and keyword arguments in Ruby 3.0" author: "mame" -translator: +translator: "hachi8833" date: 2019-12-12 12:00:00 +0000 -lang: en +lang: ja --- -This article explains the planned incompatibility of keyword arguments in Ruby 3.0 +本記事では、Ruby 3.0で予定されているキーワード引数の非互換性について解説します。 -## tl;dr +## 概要 -In Ruby 3.0, positional arguments and keyword arguments will be separated. Ruby 2.7 will warn for behaviors that will change in Ruby 3.0. If you see the following warnings, you need to update your code: +Ruby 3.0では、位置引数とキーワード引数が分離されます。Ruby 3.0で変更される振る舞いはRuby 2.7でwarningを表示します。以下のいずれかのwarningが表示される場合は、コードのアップデートが必要です。 * `Using the last argument as keyword parameters is deprecated`, or * `Passing the keyword argument as the last hash parameter is deprecated`, or * `Splitting the last argument into positional and keyword parameters is deprecated` -In most cases, you can avoid the incompatibility by adding the _double splat_ operator. It explicitly specifies passing keyword arguments instead of a `Hash` object. Likewise, you may add braces `{}` to explicitly pass a `Hash` object, instead of keyword arguments. Read the section "Typical cases" below for more details. +この非互換性は、double splat演算子(`**`)を追加することでほぼ回避できます。これにより、`Hash`オブジェクトではなくキーワード引数を渡すことが明示的に指定されます。同様に、キーワード引数ではなく`Hash`オブジェクトを明示的に渡したい場合は中かっこ(`{}`)を追加できます。詳しくは後述の「典型的なケース」をご覧ください。 -In Ruby 3, a method delegating all arguments must explicitly delegate keyword arguments in addition to positional arguments. If you want to keep the delegation behavior found in Ruby 2.7 and earlier, use `ruby2_keywords`. See the "Handling argument delegation" section below for more details. +Ruby 3では、すべての引数を委譲するメソッドで、位置引数の他に必ずキーワード引数も明示的に委譲しなければなりません。Ruby 2.7以前の委譲の振る舞いを変えたくない場合は、`ruby2_keywords`をお使いください。詳しくは後述の「引数の委譲の扱いについて」をご覧ください。 -## Typical cases +## よくあるケース -Here is the most typical case. You can use double splat operator (`**`) to pass keywords instead of a Hash. +以下はもっともよくあるケースです。Hashではなくキーワードを渡すのにdouble splat演算子(`**`)を使えます。 {% highlight ruby %} -# This method accepts only a keyword argument +# このメソッドはキーワード引数のみを受け取る def foo(k: 1) p k end h = { k: 42 } -# This method call passes a positional Hash argument -# In Ruby 2.7: The Hash is automatically converted to a keyword argument -# In Ruby 3.0: This call raises an ArgumentError +# このメソッド呼び出しは位置引数としてHashを渡している +# Ruby 2.7: このHashは自動でキーワード引数に変換される +# Ruby 3.0: この呼び出しはArgumentErrorになる foo(h) # => demo.rb:11: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call # demo.rb:2: warning: The called method `foo' is defined here # 42 -# If you want to keep the behavior in Ruby 3.0, use double splat +# この振る舞いをRuby 3.0で変えたくない場合はdouble splatを用いる foo(**h) #=> 42 {% endhighlight %} -Here is another case. You can use braces (`{}`) to pass a Hash instead of keywords explicitly. +別の例: キーワード引数ではなくHashを明示的に渡す場合は中かっこ(`{}`)を使います。 {% highlight ruby %} -# This method accepts one positional argument and a keyword rest argument +# このメソッドは位置引数を1個、残りはキーワード引数を受け取る def bar(h, **kwargs) p h end -# This call passes only a keyword argument and no positional arguments -# In Ruby 2.7: The keyword is converted to a positional Hash argument -# In Ruby 3.0: This call raises an ArgumentError +# この呼び出しではキーワード引数のみが渡され、位置引数は渡されない +# Ruby 2.7: このキーワード引数は自動でHash引数に変換される +# Ruby 3.0: この呼び出しはArgumentErrorになる bar(k: 42) # => demo2.rb:9: warning: Passing the keyword argument as the last hash parameter is deprecated # demo2.rb:2: warning: The called method `bar' is defined here # {:k=>42} -# If you want to keep the behavior in Ruby 3.0, write braces to make it an -# explicit Hash +# この振る舞いをRuby 3.0で変えたくない場合は +# 中かっこで明示的にHashにする bar({ k: 42 }) # => {:k=>42} {% endhighlight %} -## What is deprecated? +## どの動作が非推奨になるか -In Ruby 2, keyword arguments can be treated as the last positional Hash argument and a last positional Hash argument can be treated as keyword arguments. +Ruby 2では、キーワード引数が末尾のハッシュ位置引数として扱われることがあります。また、末尾のハッシュ引数がキーワード引数として扱われることもあります。 -Because the automatic conversion is sometimes too complex and troublesome as described in the final section. So it's now deprecated in Ruby 2.7 and will be removed in Ruby 3. In other words, keyword arguments will be completely separated from positional one in Ruby 3. So when you want to pass keyword arguments, you should always use `foo(k: expr)` or `foo(**expr)`. If you want to accept keyword arguments, in principle you should always use `def foo(k: default)` or `def foo(k:)` or `def foo(**kwargs)`. +この自動変換は場合によっては複雑になりすぎてしまい、本記事末尾で後述するようにトラブルの原因になることがあります。そのため、この自動変換をRuby 2.7で非推奨とし、Ruby 3.0で廃止する予定です。言い換えると、Ruby 3.0のキーワード引数は位置引数と完全に分離されることになります。つまり、キーワード引数を渡したい場合は、常に`foo(k: expr)`または`foo(**expr)`の形にすべきです。(メソッド定義で)キーワード引数を受け取りたい場合は、原則として常に以下のいずれかの形にすべきです。 -Note that Ruby 3.0 doesn't behave differently when calling a method which doesn't accept keyword arguments with keyword arguments. For instance, the following case is not going to be deprecated and will keep working in Ruby 3.0. The keyword arguments are still treated as a positional Hash argument. +* `def foo(k: default)` +* `def foo(k:)` +* `def foo(**kwargs)` + +なお、キーワード引数を受け取らないメソッドを呼び出すときにキーワード引数を渡した場合の振る舞いは、Ruby 3.0でも変わらない点にご注意ください。たとえば、以下のケースは非推奨にはならず、Ruby 3.0でも引き続き動作します(このキーワード引数は引き続きHash位置引数として扱われます)。 {% highlight ruby %} def foo(kwargs = {}) @@ -82,9 +86,9 @@ end foo(k: 1) #=> {:k=>1} {% endhighlight %} -This is because this style is used very frequently, and there is no ambiguity in how the argument should be treated. Prohibiting this conversion would result in additional incompatibility for little benefit. +変わらない理由は、このスタイルが非常によく用いられていることと、この呼び出し方法では引数の扱いに曖昧な点がないためです。この振る舞いまで禁止してしまうと、得られるメリットが少ないうえに非互換性がさらに増えてしまいます。 -However, this style is not recommended in new code, unless you are often passing a Hash as a positional argument, and are also using keyword arguments. Otherwise, use double splat: +ただし今後新しいコードを書く場合、このスタイルはおすすめできません(Hashを位置引数として渡す頻度が高く、かつキーワード引数も使う場合を除く)。代わりに、次のようにdouble splat(`**`)をお使いください。 {% highlight ruby %} def foo(**kwargs) @@ -94,21 +98,21 @@ end foo(k: 1) #=> {:k=>1} {% endhighlight %} -## Will my code break on Ruby 2.7? +## Q: 自分のコードはRuby 2.7で動かなくなりますか? -A short answer is "maybe not". +手短かに言うと「壊れない可能性はあります」。 -The changes in Ruby 2.7 are designed as a migration path towards 3.0. While in principle, Ruby 2.7 only warns against behaviors that will change in Ruby 3, it includes some incompatible changes we consider to be minor. See the "Other minor changes" section for details. +Ruby 2.7におけるこの変更は、3.0への移行パスとして設計されています。あくまで原則としてですが、Ruby 2.7ではRuby 3.0で変更される振る舞いについてwarningを出すにとどめており、warningの中には私たちが微細とみなしている変更点も若干含まれます。詳しくは後述の「その他の微細な変更点」をご覧ください。 -Except for the warnings and minor changes, Ruby 2.7 attempts to keep the compatibility with Ruby 2.6. So, your code will probably work on Ruby 2.7, though it may emit warnings. And by running it on Ruby 2.7, you can check if your code is ready for Ruby 3.0. +Ruby 2.7では、warningが表示される点と微細な変更点以外を除いてRuby 2.6との互換性を保とうとしています。つまり、あなたのコードはRuby 2.7でもおそらく動作しますが、warningが表示される可能性はあります。あなたのコードをRuby 2.7で実行すれば、Ruby 3.0の準備ができているかどうかをチェックできます。 -If you want to disable the deprecation warnings, please use a command-line argument `-W:no-deprecated` or add `Warning[:deprecated] = false` to your code. +非推奨のwarningを無効にしたい場合は、コマンドライン引数`-W:no-deprecated`を使うか、コードに`Warning[:deprecated] = false`を追加します。 -## Handling argument delegation +## 引数の委譲の扱いについて -### Ruby 2.6 or prior +### Ruby 2.6以前の場合 -In Ruby 2, you can write a delegation method by accepting a `*rest` argument and a `&block` argument, and passing the two to the target method. In this behavior, the keyword arguments are also implicitly handled by the automatic conversion between positional and keyword arguments. +Ruby 2では、以下のように1個の`*rest`引数と1個の`&block`引数を受け付けて、この2つの引数を委譲先メソッド(以下の`target`)に渡すことで委譲メソッドを書けます。この振る舞いでは、(1つ以上の)キーワード引数も「位置引数<=>キーワード引数の自動変換」によって暗黙的に扱われます。 {% highlight ruby %} def foo(*args, &block) @@ -116,9 +120,9 @@ def foo(*args, &block) end {% endhighlight %} -### Ruby 3 +### Ruby 3の場合 -You need to explicitly delegate keyword arguments. +以下のようにキーワード引数を明示的に委譲する必要があります。 {% highlight ruby %} def foo(*args, **kwargs, &block) @@ -126,7 +130,7 @@ def foo(*args, **kwargs, &block) end {% endhighlight %} -Alternatively, if you do not need compatibility with Ruby 2.6 or prior and you don't alter any arguments, you can use the new delegation syntax (`...`) that is introduced in Ruby 2.7. +別の方法として、Ruby 2.6以前との互換性を考慮する必要がなく、かつ引数を一切改変しないのであれば、以下のようにRuby 2.7で新しく導入される委譲構文(`...`)を利用できます。 {% highlight ruby %} def foo(...) @@ -134,9 +138,9 @@ def foo(...) end {% endhighlight %} -### Ruby 2.7 +### Ruby 2.7の場合 -In short: use `Module#ruby2_keywords` and delegate `*args, &block`. +手短かに言うと、以下のように`Module#ruby2_keywords`を用い、`*args, &block`を委譲します。 {% highlight ruby %} ruby2_keywords def foo(*args, &block) @@ -144,13 +148,13 @@ ruby2_keywords def foo(*args, &block) end {% endhighlight %} -`ruby2_keywords` accepts keyword arguments as the last Hash argument, and passes it as keyword arguments when calling the other method. +`ruby2_keywords`を指定すると、キーワード引数を末尾のHash引数として受け取れるようになり、他のメソッドを呼び出すときにそれをキーワード引数として渡せます。 -In fact, Ruby 2.7 allows the new style of delegation in many cases. However, there is a known corner case. See the next section. +実際、Ruby 2.7では多くの場面でこの新しい委譲のスタイルを利用できます。ただし1つ既知のエッジケースがあります。次をご覧ください。 -### A compatible delegation that works on Ruby 2.6, 2.7 and Ruby 3 +### Ruby 2.6 / 2.7 / 3で互換性のある委譲スタイル -In short: use `Module#ruby2_keywords` again. +手短かに言うと、ここも「`Module#ruby2_keywords`を使う」となります。 {% highlight ruby %} ruby2_keywords def foo(*args, &block) @@ -158,16 +162,16 @@ ruby2_keywords def foo(*args, &block) end {% endhighlight %} -Unfortunately, we need to use the old-style delegation (i.e., no `**kwargs`) because Ruby 2.6 or prior does not handle the new delegation style correctly. This is one of the reasons of the keyword argument separation; the details are described in the final section. And `ruby2_keywords` allows you to run the old style even in Ruby 2.7 and 3.0. As there is no `ruby2_keywords` defined in 2.6 or prior, please use the [ruby2_keywords gem](https://rubygems.org/gems/ruby2_keywords) or define it yourself: +残念ながら、Ruby 2.6以前では新しい委譲スタイルを正しく扱えないため、旧来の委譲スタイル(`**kwargs`を使わないなど)を使う必要があります。これは、キーワード引数を分離した理由のひとつでもあります(詳しくは本記事末尾をご覧ください)。`ruby2_keywords`を用いれば、Ruby 2.7や3.0でも旧来の委譲スタイルを引き続き利用できます。2.6以前のRubyでは`ruby2_keywords`が定義されていないので、[ruby2_keywords](https://rubygems.org/gems/ruby2_keywords) gemを使うか、以下を手動で定義します。 {% highlight ruby %} def ruby2_keywords(*) end if RUBY_VERSION < "2.7" {% endhighlight %} ---- +* * * * * -If your code doesn't have to run on Ruby 2.6 or older, you may try the new style in Ruby 2.7. In almost all cases, it works. Note that, however, there are unfortunate corner cases as follows: +自分のコードがRuby 2.6以前で動かなくても構わないのであれば、Ruby 2.7で新しいスタイルを試してもよいでしょう。ほぼほぼ間違いなく動作しますが、以下のようなエッジケースを運悪く踏むこともあります。 {% highlight ruby %} def target(*args) @@ -178,35 +182,34 @@ def foo(*args, **kwargs, &block) target(*args, **kwargs, &block) end -foo({}) #=> Ruby 2.7: [] ({} is dropped) -foo({}, **{}) #=> Ruby 2.7: [{}] (You can pass {} by explicitly passing "no" keywords) +foo({}) #=> Ruby 2.7: [] ({}を含んでいない) +foo({}, **{}) #=> Ruby 2.7: [{}] ({}を渡せば、キーワード引数が「ない」ことを明示できる) {% endhighlight %} -An empty Hash argument is automatically converted and absorbed into `**kwargs`, and the delegation call removes the empty keyword hash, so no argument is passed to `target`. As far as we know, this is the only corner case. +上のコードでは、空のHash引数が自動的に変換されて`**kwargs`に吸い込まれ、この空のキーワードハッシュは委譲の呼び出しで削除されます。このため、`targe`には引数がまったく渡されなくなります。私たちが把握している範囲では、これが唯一のエッジケースです。 -As noted in the last line, you can work around this issue by using `**{}`. +上のコードの最下部に書いたように、`**{}`を渡すことでこの問題を回避できます。 -If you really worry about the portability, use `ruby2_keywords`. (Acknowledge that Ruby 2.6 or before themselves have tons of corner cases in keyword arguments. :-) -`ruby2_keywords` might be removed in the future after Ruby 2.6 reaches end-of-life. At that point, we recommend to explicitly delegate keyword arguments (see Ruby 3 code above). +移植性がどうしても不安な場合は`ruby2_keywords`をお使いください(Ruby 2.6以前ではキーワード引数周りで膨大なエッジケースが存在していることを知っておいてください)。`ruby2_keywords`は、今後Ruby 2.6が役目を終えたときに削除される可能性があります。現時点で私たちがおすすめできるのは、キーワード引数を明示的に委譲することです(上述のRuby 3向けのコードを参照)。 -## Other minor changes +## その他の微細な変更点 -There are three minor changes about keyword arguments in Ruby 2.7. +Ruby 2.7のキーワード引数では、この他に以下の3つのマイナーチェンジが行われています。 -### 1. Non-Symbol keys are allowed in keyword arguments +### 1\. キーワード引数で非シンボルキーを利用できるようになった -In Ruby 2.6 or before, only Symbol keys were allowed in keyword arguments. In Ruby 2.7, keyword arguments can use non-Symbol keys. +Ruby 2.6以前のキーワード引数では、シンボル形式のキーしか利用できませんでした。Ruby 2.7のキーワード引数では、以下のようにシンボル形式でないキーを利用できるようになります。 {% highlight ruby %} def foo(**kwargs) kwargs end foo("key" => 42) - #=> Ruby 2.6 or before: ArgumentError: wrong number of arguments - #=> Ruby 2.7 or later: {"key"=>42} + #=> Ruby 2.6以前: ArgumentError: wrong number of arguments + #=> Ruby 2.7以降: {"key"=>42} {% endhighlight %} -If a method accepts both optional and keyword arguments, the Hash object that has both Symbol keys and non-Symbol keys was split in two in Ruby 2.6. In Ruby 2.7, both are accepted as keywords because non-Symbol keys are allowed. +あるメソッドがオプション引数とキーワード引数を両方とも受け付ける場合、Ruby 2.6では以下のようにシンボル形式のキーと非シンボルキーを両方持つHashオブジェクトが2つに分割されていました。Ruby 2.7では非シンボルキーを利用できるので、どちらも受け取れます。 {% highlight ruby %} def bar(x=1, **kwargs) @@ -217,12 +220,12 @@ bar("key" => 42, :sym => 43) #=> Ruby 2.6: [{"key"=>42}, {:sym=>43}] #=> Ruby 2.7: [1, {"key"=>42, :sym=>43}] -# Use braces to keep the behavior +# 振る舞いを変えたくない場合は中かっこ{}を使う bar({"key" => 42}, :sym => 43) #=> Ruby 2.6 and 2.7: [{"key"=>42}, {:sym=>43}] {% endhighlight %} -Ruby 2.7 still splits hashes with a warning if passing a Hash or keyword arguments with both Symbol and non-Symbol keys to a method that accepts explicit keywords but no keyword rest argument (`**kwargs`). This behavior will be removed in Ruby 3, and an `ArgumentError` will be raised. +Ruby 2.7では、キーワード引数を明示的に受け付けるがキーワードrest引数(`**kwargs`)を受け取らないメソッドに対して、シンボル形式のキーと非シンボルキーが両方混じったHashやキーワード引数を渡すと、引き続きハッシュを分割して警告を表示します。この振る舞いはRuby 3で廃止されて`ArgumentError`にする予定です。 {% highlight ruby %} def bar(x=1, sym: nil) @@ -230,15 +233,15 @@ def bar(x=1, sym: nil) end bar("key" => 42, :sym => 43) -# Ruby 2.6 and 2.7: => [{"key"=>42}, 43] +# Ruby 2.6と2.7: => [{"key"=>42}, 43] # Ruby 2.7: warning: Splitting the last argument into positional and keyword parameters is deprecated # warning: The called method `bar' is defined here # Ruby 3.0: ArgumentError {% endhighlight %} -### 2. Double splat with an empty hash (`**{}`) passes no arguments +### 2\. double splatを付けた空ハッシュ(`**{}`)で引数を渡さないようになった -In Ruby 2.6 or before, passing `**empty_hash` passes an empty Hash as a positional argument. In Ruby 2.7 or later, it passes no arguments. +Ruby 2.6以前は、`**empty_hash`を渡すと位置引数に空のハッシュが渡されました(`[{}]`)。Ruby 2.7以降では引数を渡さなくなります。 {% highlight ruby %} def foo(*args) @@ -247,13 +250,13 @@ end empty_hash = {} foo(**empty_hash) - #=> Ruby 2.6 or before: [{}] - #=> Ruby 2.7 or later: [] + #=> Ruby 2.6以前: [{}] + #=> Ruby 2.7以降: [] {% endhighlight %} -Note that `foo(**{})` passes nothing in both Ruby 2.6 and 2.7. In Ruby 2.6 and before, `**{}` is removed by the parser, and in Ruby 2.7 and above, it is treated the same as `**empty_hash`, allowing for an easy way to pass no keyword arguments to a method. +なお、`foo(**{})`はRuby 2.6以前とRuby 2.7のどちらの場合も引数を渡さず、`**{}`がパーサーによって削除される点にご注意ください。また、Ruby 2.7以降ではどちらも`**empty_hash`として同じに扱われるので、メソッドにキーワード引数を渡さないようにする指定が楽に行なえます。 -In Ruby 2.7, when calling a method with an insufficient number of required positional arguments, `foo(**empty_hash)` passes an empty hash with a warning emitted, for compatibility with Ruby 2.6. This behavior will be removed in 3.0. +Ruby 2.7では、あるメソッド呼び出しで必須とされる位置引数の個数が不足している場合、Ruby 2.6との互換性を保つために`foo(**empty_hash)`は空のハッシュを渡してwarningを表示します。この振る舞いはRuby 3.0で廃止されます。 {% highlight ruby %} def foo(x) @@ -262,51 +265,51 @@ end empty_hash = {} foo(**empty_hash) - #=> Ruby 2.6 or before: {} + #=> Ruby 2.6以前: {} #=> Ruby 2.7: warning: Passing the keyword argument as the last hash parameter is deprecated # warning: The called method `foo' is defined here #=> Ruby 3.0: ArgumentError: wrong number of arguments {% endhighlight %} -### 3. The no-keyword-arguments syntax (`**nil`) is introduced +### 3\. キーワード引数を受け取らないことを表す構文(`**nil`)が導入される -You can use `**nil` in a method definition to explicitly mark the method accepts no keyword arguments. Calling such methods with keyword arguments will result in an `ArgumentError`. (This is actually a new feature, not an incompatibility) +メソッド定義で`**nil`を用いることで、そのメソッドがキーワード引数を受け取らないことを明示的に示せるようになります。このメソッドを呼び出すときにキーワード引数を渡すと`ArgumentError`が表示されます(これは非互換性ではなく、事実上新機能です)。 {% highlight ruby %} def foo(*args, **nil) end foo(k: 1) - #=> Ruby 2.7 or later: no keywords accepted (ArgumentError) + #=> Ruby 2.7以降: no keywords accepted (ArgumentError) {% endhighlight %} -This is useful to make it explicit that the method does not accept keyword arguments. Otherwise, the keywords are absorbed in the rest argument in the above example. If you extend a method to accept keyword arguments, the method may have incompatibility as follows: +この新構文は、メソッドがキーワード引数を受け取らないことを明示的に指定するのに有用です。これを使わない場合、キーワード引数は上述の例の他の引数に吸い込まれます。メソッドを拡張してキーワード引数を受け取るようにする場合、以下のような非互換性が発生する可能性があります。 {% highlight ruby %} -# If a method accepts rest argument and no `**nil` +# メソッドは残りの引数を受け取るが、`**nil`はない状態 def foo(*args) p args end -# Passing keywords are converted to a Hash object (even in Ruby 3.0) +# キーワード引数はHashオブジェクトに変換される(Ruby 3.0でも同じ) foo(k: 1) #=> [{:k=>1}] -# If the method is extended to accept a keyword +# メソッドがキーワード引数を受け取るよう拡張した場合 def foo(*args, mode: false) p args end -# The existing call may break +# 以下の呼び出しが壊れる可能性がある foo(k: 1) #=> ArgumentError: unknown keyword k {% endhighlight %} -## Why we're deprecating the automatic conversion +## 自動変換を非推奨に変える理由 -The automatic conversion initially appeared to be a good idea, and worked well in many cases. However, it had too many corner cases, and we have received many bug reports about the behavior. +当初、自動変換はうまいアイデアに思われていて、多くの場合問題なく機能していました。しかし、エッジケースがあまりにも多く、これまでこの振る舞いに関するバグレポートを山のように受け取りました。 -Automatic conversion does not work well when a method accepts optional positional arguments and keyword arguments. Some people expect the last Hash object to be treated as a positional argument, and others expect it to be converted to keyword arguments. +自動変換は、オプションの位置引数とキーワード引数をどちらも受け取るメソッドではうまく動きません。末尾のHashオブジェクトを位置引数として扱うことを期待する人々もいれば、末尾のHashオブジェクトをキーワード引数として扱うことを期待する人々もいました。 -Here is one of the most confusing cases: +最も混乱を呼ぶケースのひとつを以下に示します。 {% highlight ruby %} def foo(x, **kwargs) @@ -317,17 +320,17 @@ def bar(x=1, **kwargs) p [x, kwargs] end -foo({}) => [{}, {}] -bar({}) => [1, {}] +foo({}) #=> [{}, {}] +bar({}) #=> [1, {}] -bar({}, **{}) => expected: [{}, {}], actual: [1, {}] +bar({}, **{}) #=> 期待は: [{}, {}]だが実際はl: [1, {}] {% endhighlight %} -In Ruby 2, `foo({})` passes an empty hash as a normal argument (i.e., `{}` is assigned to `x`), while `bar({})` passes a keyword argument (i.e, `{}` is assigned to `kwargs`). So `any_method({})` is very ambiguous. +Ruby 2の場合、`foo({})`は空のハッシュを通常の引数として1つ渡しますが(`x`に`{}`が代入されるなど)、`bar({})`はキーワード引数を1つ渡します(`kwargs`に`{}`が代入されるなど)。つまり、`any_method({})`は極めてあいまいになります。 -You may think of `bar({}, **{})` to pass the empty hash to `x` explicitly. Surprisingly, it does not work as you expected; it still prints `[1, {}]` in Ruby 2.6. This is because `**{}` is ignored by the parser in Ruby 2.6, and the first argument `{}` is automatically converted to keywords (`**kwargs`). In this case, you need to call `bar({}, {})`, which is very weird. +「`bar({}, **{})`は`x`に明示的に空のハッシュを渡すのでは?」と考える人もいるかもしれませんが、驚いたことに、この期待は裏切られます。Ruby 2.6では`[1, {}]`が出力されるのです。理由は、`**{}`がRuby 2.6のパーサーで無視されるのと、1番目の引数`{}`が自動的にキーワード引数(`**kwargs`)に変換されるためです。この場合`bar({}, {})`という形で呼び出す必要がありますが、これではあまりに見苦しくなります。 -The same issues also apply to methods that accept rest and keyword arguments. This makes explicit delegation of keyword arguments not work. +同じ問題は、残りの引数とキーワード引数を受け取るメソッドにも当てはまります。そのせいで、以下のようなキーワード引数の明示的な委譲は動作しません。 {% highlight ruby %} def target(*args) @@ -338,18 +341,18 @@ def foo(*args, **kwargs, &block) target(*args, **kwargs, &block) end -foo() #=> Ruby 2.6 or before: [{}] - #=> Ruby 2.7 or later: [] +foo() #=> Ruby 2.6以前: [{}] + #=> Ruby 2.7以降: [] {% endhighlight %} -`foo()` passes no arguments, but `target` receives an empty hash argument in Ruby 2.6. This is because the method `foo` delegates keywords (`**kwargs`) explicitly. When `foo()` is called, `args` is an empty Array, `kwargs` is an empty Hash, and `block` is `nil`. And then `target(*args, **kwargs, &block)` passes an empty Hash as an argument because `**kwargs` is automatically converted to a positional Hash argument. +`foo()`には引数がありませんが、Ruby 2.6では空のハッシュ引数が`target`に渡されます。理由は、メソッド`foo`が明示的にキーワード(`**kwargs`)を委譲しているためです。`foo()`が呼び出されると、`args`は空のArrayになり、`kwargs`は空のHashになります。そして`target(*args, **kwargs, &block)`は空のHashを引数として1つ渡します。理由は、`**kwargs`が自動的にHash位置引数に変換されるためです。 -The automatic conversion not only confuses people but also makes the method less extensible. See [[Feature #14183]](https://bugs.ruby-lang.org/issues/14183) for more details about the reasons for the change in behavior, and why certain implementation choices were made. +自動変換は開発者を混乱させるのみならず、メソッドの拡張性も弱めてしまいます。振る舞いが変更された理由や、特定の実装が選択された理由について詳しくは[Feature #14183](https://bugs.ruby-lang.org/issues/14183)をご覧ください。 -## Acknowledgment +## 謝辞 -This article was kindly reviewed (or even co-authored) by Jeremy Evans and Benoit Daloze. +本記事はJeremy EvansとBenoit Dalozeによる丁寧なレビュー(共著と言ってもよいくらいです)をいただきました。 -## History +## 更新履歴 -* Updated 2019-12-25: In 2.7.0-rc2, the warning message was slightly changed, and an API to suppress the warnings was added. +* 更新 2019-12-25: 2.7.0-rc2でwarningメッセージが若干変更され、warning抑制APIが追加された。 From 14e04bc34672d0e27ba23212213843b764d3ad73 Mon Sep 17 00:00:00 2001 From: hachi8833 Date: Thu, 30 Jan 2020 16:49:40 +0900 Subject: [PATCH 0004/1292] Fix untranslated lines --- ...ation-of-positional-and-keyword-arguments-in-ruby-3-0.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md index 5e80e231d5..b9aec21a12 100644 --- a/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md +++ b/ja/news/_posts/2019-12-12-separation-of-positional-and-keyword-arguments-in-ruby-3-0.md @@ -1,6 +1,6 @@ --- layout: news_post -title: "Separation of positional and keyword arguments in Ruby 3.0" +title: "Ruby 3.0における位置引数とキーワード引数の分離について" author: "mame" translator: "hachi8833" date: 2019-12-12 12:00:00 +0000 @@ -13,8 +13,8 @@ lang: ja Ruby 3.0では、位置引数とキーワード引数が分離されます。Ruby 3.0で変更される振る舞いはRuby 2.7でwarningを表示します。以下のいずれかのwarningが表示される場合は、コードのアップデートが必要です。 -* `Using the last argument as keyword parameters is deprecated`, or -* `Passing the keyword argument as the last hash parameter is deprecated`, or +* `Using the last argument as keyword parameters is deprecated` +* `Passing the keyword argument as the last hash parameter is deprecated` * `Splitting the last argument into positional and keyword parameters is deprecated` この非互換性は、double splat演算子(`**`)を追加することでほぼ回避できます。これにより、`Hash`オブジェクトではなくキーワード引数を渡すことが明示的に指定されます。同様に、キーワード引数ではなく`Hash`オブジェクトを明示的に渡したい場合は中かっこ(`{}`)を追加できます。詳しくは後述の「典型的なケース」をご覧ください。 From 58db0375aef375d8a929d00b5f4d58372b7821a7 Mon Sep 17 00:00:00 2001 From: twlixin Date: Mon, 16 Nov 2020 01:18:45 +0900 Subject: [PATCH 0005/1292] Create 2020-04-05-support-of-ruby-2-4-has-ended.md --- ...020-04-05-support-of-ruby-2-4-has-ended.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 zh_tw/news/_posts/2020-04-05-support-of-ruby-2-4-has-ended.md diff --git a/zh_tw/news/_posts/2020-04-05-support-of-ruby-2-4-has-ended.md b/zh_tw/news/_posts/2020-04-05-support-of-ruby-2-4-has-ended.md new file mode 100644 index 0000000000..0dfe1bbb6b --- /dev/null +++ b/zh_tw/news/_posts/2020-04-05-support-of-ruby-2-4-has-ended.md @@ -0,0 +1,37 @@ +--- +layout: news_post +title: "Ruby 2.4 官方支持終了" +author: "usa" +translator: "twlixin" +date: 2020-04-05 12:00:00 +0000 +lang: zh_tw +--- + +Ruby 2.4 系列的官方支持終了期間之宣布。 + +昨年 4 月以來的 1 年間、Ruby 2.4系列處於安全維護期。正如先前所宣布的,官方支持將於2020年3月31日結束。 +之後,有簡單的錯誤修復或者即使發現安全問題,也不會針對Ruby 2.4系列發布新版本。 + +2020年3月31日,Ruby 2.4系列的最終版本2.4.10發布,這只是為了讓使用者更有時間轉移到較新的版本系列。 +如果您當前正在使用Ruby 2.4系列,請盡快轉換到較新的版本系列。 + +##關於當前支持的版本系列 + +### Ruby 2.7系列 + +目前處於正常維護階段。 +随時會更新版本,包括發現到的錯誤之修復。 +此外,如果發現嚴重的安全問題,將進行相對應的緊急版本更新。 + +### Ruby 2.6 系列 + +目前處於正常維護階段。 +随時會更新版本,包括發現到的錯誤之修復。 +此外,如果發現嚴重的安全問題,將進行相對應的緊急版本更新。 + +### Ruby 2.5 系列 + +目前處於安全維護期。 +不會針對一般的錯誤作修復。 +如果發現嚴重的安全問題,將進行相應的緊急版本更新。 +預定將於2021年3月結束官方的支持。 From 34f9ecd78c97a889a82c546426fb6bff485236da Mon Sep 17 00:00:00 2001 From: Benoit Tigeot Date: Tue, 8 Dec 2020 22:38:06 +0100 Subject: [PATCH 0006/1292] Remove duplicated "Find pattern is added." --- .../_posts/2020-12-08-ruby-3-0-0-preview2-released.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md index e9f1a21937..ffb099dc9a 100644 --- a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md +++ b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md @@ -172,16 +172,6 @@ end ``` ruby def square(x) = x * x ``` -* Find pattern is added. - ``` ruby - case ["a", 1, "b", "c", 2, "d", "e", "f", 3] - in [*pre, String => x, String => y, *post] - p pre #=> ["a", 1] - p x #=> "b" - p y #=> "c" - p post #=> [2, "d", "e", "f", 3] - end - ``` * `Hash#except` is now built-in. ``` ruby h = { a: 1, b: 2, c: 3 } From 0fe447a4203e36059f05b0598e49d099378115fe Mon Sep 17 00:00:00 2001 From: Beyar Date: Tue, 8 Dec 2020 23:03:34 +0100 Subject: [PATCH 0007/1292] Update 2020-12-08-ruby-3-0-0-preview2-released.md Fixed spelling --- en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md index e9f1a21937..d3c2f7260d 100644 --- a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md +++ b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md @@ -92,7 +92,7 @@ You can make multiple ractors and you can run them in parallel. Ractor enables y To limit sharing of objects, Ractor introduces several restrictions to the Ruby's syntax (without multiple Ractors, there is no restriction). -The specification and implmentation are not matured and may be changed in the future, so this feature is marked as experimental and show the "experimental feature" warning when the first `Ractor.new`. +The specification and implementation are not matured and may be changed in the future, so this feature is marked as experimental and show the "experimental feature" warning when the first `Ractor.new`. The following small program calculates `n.prime?` (`n` is relatively a big integer) in parallel with two ractors. You will confirm that the program execution is about x2 times faster ompare with the sequential program on the parallel computer. From ccf7d957b9c7cfd937d403f1b5aa0bcb146b3ac1 Mon Sep 17 00:00:00 2001 From: Beyar Date: Tue, 8 Dec 2020 23:06:47 +0100 Subject: [PATCH 0008/1292] Update 2020-12-08-ruby-3-0-0-preview2-released.md --- en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md index d3c2f7260d..afc7f6e482 100644 --- a/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md +++ b/en/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md @@ -94,7 +94,7 @@ To limit sharing of objects, Ractor introduces several restrictions to the Ruby' The specification and implementation are not matured and may be changed in the future, so this feature is marked as experimental and show the "experimental feature" warning when the first `Ractor.new`. -The following small program calculates `n.prime?` (`n` is relatively a big integer) in parallel with two ractors. You will confirm that the program execution is about x2 times faster ompare with the sequential program on the parallel computer. +The following small program calculates `n.prime?` (`n` is relatively a big integer) in parallel with two ractors. You will confirm that the program execution is about x2 times faster compared to the sequential program on the parallel computer. ``` ruby require 'prime' From d0c75879cfc1bd97b551e5c7df866ee280bcf320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0smail=20Ar=C4=B1l=C4=B1k?= Date: Sat, 12 Dec 2020 17:28:48 +0300 Subject: [PATCH 0009/1292] Translate 3.0.0-preview2 released post (tr) (#2565) --- ...2020-12-08-ruby-3-0-0-preview2-released.md | 297 ++++++++++++++++++ 1 file changed, 297 insertions(+) create mode 100644 tr/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md diff --git a/tr/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md b/tr/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md new file mode 100644 index 0000000000..b4d7c44106 --- /dev/null +++ b/tr/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md @@ -0,0 +1,297 @@ +--- +layout: news_post +title: "Ruby 3.0.0 Önizleme 2 Yayınlandı" +author: "naruse" +translator: "ismailarilik" +date: 2020-12-08 00:00:00 +0000 +lang: tr +--- + +Ruby 3.0.0-preview2'nin yayınlandığını duyurmaktan memnuniyet duyuyoruz. + +Bu sürüm birçok yeni özellik ve performans iyileştirmesi içermektedir. + +## Statik Analiz + +### RBS + +RBS, Ruby programlarındaki tipleri tanımlamada kullanılan bir dildir. + +RBS'yi destekleyen tip kontrol edicileri (TypeProf ve diğer araçlar da dahil), RBS tanımlamaları ile birlikte Ruby programlarını çok daha iyi anlayacaklardır. + +RBS ile sınıfların ve modüllerin tanımını yazabilirsiniz: bir sınıfta tanımlanmış metodlar, örnek değişkenleri ve bu değişkenlerin tipleri, ve miras/mix-in ilişkisi. + +RBS'nin amacı Ruby programlarında sıkça görülen desenleri desteklemektir. +RBS, union tiplerinin de dahil olduğu gelişmiş tipleri, metod aşırı yüklemeyi, ve genelleyicileri yazmaya izin verir. +Ayrıca _arayüz tipleri_ ile ördek tiplemesini de destekler. + +Ruby 3.0 `rbs` gem'i ile gelmektedir, bu gem RBS ile yazılmış tip tanımlarını ayrıştırma ve işlemeye izin verir. +Aşağıdaki kod sınıf, modül ve sabit tanımlamalarını içeren, RBS için küçük bir örnektir. + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|`, union tip anlamına gelmektedir, `User` ya da `Bot`. + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # Metod aşırı yükleme destekleniyor. + | (File, from: User | Bot) -> Message + end +end +``` + +Daha fazla ayrıntı için [rbs gem'inin README](https://github.com/ruby/rbs)'sine bakınız. + +### TypeProf + +TypeProf, Ruby ile paketlenmiş bir tip analizi aracıdır. + +Şu anda TypeProf, bir çeşit tip çıkarımı olarak hizmet vermektedir. + +TypeProf, sade (tiplerin belirtilmediği) Ruby kodunu okur, hangi metodların tanımlandığını ve bu metodların nasıl kullanıldığını analiz eder, ve RBS biçiminde prototip bir tip imzası oluşturur. + +İşte basit bir TypeProf demosu. + +Örnek bir girdi: + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +Örnek bir çıktı: + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +TypeProf'u, girdiyi "test.rb" olarak kaydederek ve "typeprof test.rb" komutunu çağırarak çalıştırabilirsiniz. + +Ayrıca [TypeProf'u çevrimiçi deneyebilirsiniz](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=). +(Burası TypeProf'u sunucu tarafında çalıştırır, yani eğer çalışmazsa kusura bakmayın!) + +Ayrıntılar için [belgelendirmeye](https://github.com/ruby/typeprof/blob/master/doc/doc.md) ve [demolara](https://github.com/ruby/typeprof/blob/master/doc/demo.md) bakın. + +TypeProf şu anda deneysel ve oturmuş değil; Ruby'nin sadece bir alt kümesi destekleniyor, ve tip hatalarının tespit edilmesi kısıtlıdır. +Fakat TypeProf, dil özelliklerinin kapsamasını, analiz performansını ve kullanılırlığı hızlıca artırmak için gelişmektedir. +Herhangi bir geri bildirime çok ihtiyacımız var. + +## Ractor (deneysel) + +Ractor, thread güvenliği endişeleri olmadan paralel çalıştırma özelliğini sağlamak için tasarlanan eşzamanlı soyutlama gibi bir aktör-modeldir. + +Birden fazla ractor yapabilirsiniz ve bunları paralelde çalıştırabilirsiniz. +Ractor thread-güvenli paralel programlar yapmanıza izin verir çünkü ractor'lar normal nesneleri paylaşmazlar. +Ractor'lar arasındaki iletişim mesaj geçirme ile desteklenir. + + + + +Nesnelerin paylaşılmasını kısıtlamak için Ractor, Ruby'nin sözdizimine bazı kısıtlamalar getirir (birden fazla Ractor yoksa, değişiklik yoktur). + +Belirtim ve gerçekleme henüz tam oturmamıştır ve ileride değişecektir, bu sebeple bu özellik deneysel olarak işaretlenmiştir ve ilk `Ractor.new`'de "deneysel özellik" uyarısı gösterilir. + +Aşağıdaki küçük program `n.prime?`'ı (`n` nispeten büyük bir tamsayıdır) iki ractor ile paralelde hesaplar. +Bu programın çalışması paralel bilgisayarda ardışık bir programa göre aşağı yukarı 2 kat daha hızlıdır. + +``` ruby +require 'prime' +# r1 ve r2'deki, tamsayıların gönderildiği n.prime? paralelde çalışır +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.recv + n.prime? + end +end +# parametreleri gönder +r1.send 2**61 - 1 +r2.send 2**61 + 15 +# 1. ve 2. deyimin sonuçlarını bekle +p r1.take #=> true +p r2.take #=> true +``` + +Daha fazla ayrıntı için [doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md)'ye bakın. + +## Fiber Zamanlayıcı + +`Fiber#scheduler` bloklayan işlemleri kesmek için tanıtılmıştır. +Bu, var olan kodu değiştirmeden hafif eşzamanlılığa izin verir. +Nasıl çalıştığının genel bir bakış için ["Beni Bekleme, Ruby 3'te Ölçeklenebilir Eşzamanlılık"](https://www.youtube.com/watch?v=Y29SSOS4UOc)'ı izleyin. + +Şu anda desteklenen sınıf ve metodlar: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` ve ilişkili metodlar (`#wait_readable`, `#gets`, `#puts`, vb. gibi). +- `IO#select` *desteklenmemektedir*. +(Async gem'ini bağlantılarla açıkla). +Bu örnek program birden çok HTTP isteğini eşzamanlı olarak gerçekleştirecektir: +(Bunu açıkla:) +1. async dışsal bir gem +2. async bu yeni özelliği kullanır + +``` ruby +require 'async' +require 'net/http' +require 'uri' +Async do + ["ruby", "python", "c"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + +## Diğer Dikkate Değer Yeni Özellikler + +* Tek satırlık desen eşleştirme şimdi `in` yerine `=>` kullanıyor. + ``` ruby + # sürüm 3.0 + {a: 0, b: 1} => {a:} + p a # => 0 + # sürüm 2.7 + {a: 0, b: 1} in {a:} + p a # => 0 + ``` +* Bulma deseni eklendi. + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` +* Sonsuz metod tanımı eklendi. + ``` ruby + def square(x) = x * x + ``` +* `Hash#except` şimdi gömülü. + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` +* Hafıza görünümü deneysel bir özellik olarak eklendi. + * Bu, uzantı kütüphaneleri arasında sayısal bir dizi ve bir biteşlem görüntüsü gibi ham bir hafıza alanını takas etmek için yeni bir C-API'ıdır. + Uzantı kütüphaneleri ayrıca şekil, öğe biçimi, vb. içeren hafıza alanlarının üstverilerini de paylaşır. + Bu gibi üstverileri kullanarak, uzantı kütüphaneleri çok boyutlu dizileri bile uygun şekilde paylaşabilirler. + Bu özellik Python'ın tampon protokolüne danışılarak tasarlanmıştır. + +## Performans iyileştirmeleri + +* Birçok geliştirme MJIT'te gerçeklenmiştir. + Ayrıntılar için NEWS'e bakınız. +* Uzun bir kodu IRB'ye yapıştırmak, Ruby 2.7.0'da gelene göre 53 kat daha hızlı. + Örneğin, [şu örnek kodu](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) yapıştırmak için gereken zaman 11.7 saniyeden 0.22 saniyeye düşmüştür. + +## 2.7'den bu yana diğer dikkate değer değişiklikler + +* Anahtar sözcük argümanları diğer argümanlardan ayrılmıştır. + * Prensipte, Ruby 2.7'de bir uyarı yazdıran kod çalışmayacaktır. + Ayrıntılar için [belgeye](https://www.ruby-lang.org/tr/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) bakınız. + * Bu arada argüman yönlendirme artık sondaki argümanları da destekliyor. + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` +* `$SAFE` özelliği tamamiyle silindi; şimdi sadece normal bir global değişken. +* Geriizleme sırası Ruby 2.5'te tersine çevrildi, fakat bu iptal edildi. + Şimdi Ruby 2.4'teki gibi bir davranış söz konusu; hata mesajı ve istisnanın meydana geldiği satır numarası ilk olarak yazdırılır, daha sonra ise çağırıcıları yazdırılır. +* Bazı standart kütüphaneler güncellendi. + * RubyGems 3.2.0.rc.1 + * Bundler 2.2.0.rc.1 + * IRB 1.2.6 + * Reline 0.1.5 +* Aşağıdaki kütüphaneler artık paketlenmiyor. + Bu özellikleri kullanmak için denk gelen gem'leri kurun. + * net-telnet + * xmlrpc +* Şu varsayılan gem'ler paketlenmiş gem'ler olarak düzenlendi. + * rexml + * rss +* Aşağıdaki stdlib dosyaları şimdi varsayılan gemler ve rubygems.org'da yayınlandı. + * abbrev + * base64 + * English + * erb + * find + * io-nonblock + * io-wait + * net-ftp + * net-http + * net-imap + * net-protocol + * nkf + * open-uri + * optparse + * resolv + * resolv-replace + * rinda + * securerandom + * set + * shellwords + * tempfile + * time + * tmpdir + * tsort + * weakref + +Daha fazla ayrıntı için [NEWS](https://github.com/ruby/ruby/blob/v3_0_0_preview2/NEWS.md)'e +ya da [işleme loglarına](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_preview2) +bakın. + +{% assign release = site.data.releases | where: "version", "3.0.0-preview2" | first %} + +Bu değişikliklerle birlikte, 2.7.0'dan bu yana [{{ release.stats.files_changed }} dosya değişti, {{ release.stats.insertions }} ekleme yapıldı(+), {{ release.stats.deletions }} silme yapıldı(-)](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0)! + +Lütfen Ruby 3.0.0-preview2'yi deneyin, ve bize herhangi bir geri bildirim verin! + +## İndirin + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Ruby nedir + +Ruby ilk olarak Matz (Yukihiro Matsumoto) tarafından 1993'te geliştirilmiştir, ve şu anda Açık Kaynak olarak geliştirilmektedir. +Birçok platformda çalışır ve tüm dünyada genellikle web geliştirmesi için kullanılır. From 0d5b4573be8ea12b72b0fa7a9ecd87ff2e3ecea0 Mon Sep 17 00:00:00 2001 From: Andrias Meisyal Date: Wed, 18 Nov 2020 23:41:33 +0700 Subject: [PATCH 0010/1292] Translate Ruby 3.0.0 Preview 1 released news (id) --- ...2020-09-25-ruby-3-0-0-preview1-released.md | 271 ++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md diff --git a/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md b/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md new file mode 100644 index 0000000000..a96108a9c0 --- /dev/null +++ b/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md @@ -0,0 +1,271 @@ +--- +layout: news_post +title: "Ruby 3.0.0 Preview 1 Dirilis" +author: "naruse" +translator: "meisyal" +date: 2020-09-25 00:00:00 +0000 +lang: id +--- + +Kami dengan senang hati mengumumkan rilis dari Ruby 3.0.0-preview1. + +Rilis ini mengenalkan sejumlah fitur baru dan perbaikan performa. + +## RBS + +RBS adalah sebuah bahasa yang mendeskripsikan tipe dari program Ruby. +*Type checker* termasuk *type-profiler* dan *tool* lainnya yang mendukung RBS +akan memahami program Ruby jauh lebih baik dengan definisi RBS. + +Anda dapat menuliskan definisi *class* dan *module*: *method* didefinisikan di +dalam *class*, *instance variables* dan tipenya, serta hubungan +*inheritance/mix-in*. RBS memiliki tujuan untuk mendukung pola yang biasanya +kita lihat dalam program Ruby dan memperbolehkan penulisan *advanced types* +yang berisi *union type*, *method overloading*, dan *generic*. RBS juga +mendukung *duck typing* dengan _interface types_. + +Ruby 3.0 dirilis dengan gem `rbs`, yang memperbolehkan untuk mem-*parse* dan +memproses definisi tipe yang ditulis di dalam RBS. + +Berikut ini adalah sebuah contoh kecil dari RBS. + +``` rbs +module ChatApp + VERSION: String + + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|` berarti union types, `User` atau `Bot`. + + def initialize: (String) -> void + + def post: (String, from: User | Bot) -> Message # Method overloading didukung. + | (File, from: User | Bot) -> Message + end +end +``` + +Lihat [README dari gem rbs](https://github.com/ruby/rbs) untuk lebih detail. + +## Ractor (eksperimental) + +*Ractor* adalah sebuah *Actor-model* seperti *concurrent abstraction* yang +didesain untuk menyediakan sebuah fitur eksekusi paralel tanpa mengkhawatirkan +*thread-safety*. + +Anda dapat membuat beberapa *ractor* dan menjalankannya secara paralel. *Ractor* +memungkinkan untuk membuat program paralel yang *thread-safe* karena *ractor* +tidak dapat membagi objek normal. Komunikasi antar *ractor* didukung oleh +*message passing*. + +Untuk membatasi pembagian objek, *Ractor* mengenalkan beberapa batasan pada +sintaks Ruby (tanpa banyak *Ractor*, maka tidak ada perubahan). + +Spesifikasi dan implementasi dari *Ractor* masih belum sempurna dan memungkinkan +adanya perubahan ke depan, sehingga fitur ini ditandai dengan eksperimental +dan peringatan fitur eksperimental akan ditampilkan ketika *Ractor* dibuat. + +Berikut adalah program kecil yang mengecek `prime?` secara paralel dengan +dua *ractor* dan memiliki kecepatan 2 kali lebih cepat dengan dua atau lebih +*core* dibanding program *sequential*. + +``` ruby +require 'prime' + +# n.prime? dengan integer r1, r2 jalan secara paralel +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.recv + n.prime? + end +end + +# parameter dikirim +r1.send 2**61 - 1 +r2.send 2**61 + 15 + +# menunggu hasil dari expr1, expr2 +p r1.take #=> true +p r2.take #=> true +``` + +Lihat [doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md) +untuk lebih detail. + +## Scheduler (eksperimental) + +`Thread#scheduler` diperkenalkan untuk menghalangi operasi *blocking*. Ini +memperbolehkan *light-weight concurrency* tanpa pengubahan kode yang sudah ada. + +Saat ini, *class*/*method* yang didukung: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `IO#wait`, `IO#read`, `IO#write` dan *method* yang berkaitan (seperti `#wait_readable`, `#gets`, `#puts` dan lainnya). +- `IO#select` *tidak didukung*. + +Titik masuk dari *concurrency* saat ini adalah `Fiber.schedule{...}`, namun +ini dapat berubah sewaktu-waktu ketika Ruby 3 dirilis. + +Sekarang, ada sebuah *test scheduler* yang tersedia di [`Async::Scheduler`](https://github.com/socketry/async/pull/56). Lihat [`doc/scheduler.md`](https://github.com/ruby/ruby/blob/master/doc/scheduler.md) +untuk lebih detail. [Feature #16786] + +**PERINGATAN**: Fitur ini masih eksperimental. Baik nama maupun fitur akan +berubah pada rilis *preview* berikutnya. + +## Fitur Baru Lainnya + +* *Rightward assignment statement* ditambahkan. + + ``` ruby + fib(10) => x + p x #=> 55 + ``` + +* Definisi *endless method* ditambahkan. + + ``` ruby + def square(x) = x * x + ``` + +* *Find pattern* ditambahkan. + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* `Hash#except` sekarang *built-in*. + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + +* *Memory view* ditambahkan sebagai sebuah fitur eksperimental + + * Ini adalah sebuah kumpulan C-API baru yang menukar sebuah area *raw memory*, seperti sebuah *numeric array* dan sebuah *bitmap image*, antara pustaka *extension*. Pustaka *extension* dapat juga membagikan *metadata* dari area *memory* yang terdiri dari bentuk, format elemen, dan sebagainya. Menggunakan semacam *metadata* seperti ini, pustaka *extension* bahkan dapat membagikan sebuah *multidimensional array* dengan tepat. Fitur ini didesain dengan merujuk pada *buffer protocol* dari Python. + +## Perbaikan performa + +* Banyak perbaikan yang telah diimplementasikan dalam MJIT. Lihat NEWS untuk detail. + +## Perubahan penting lainnya sejak 2.7 + +* *Keyword argument* dipisahkan dari *argument* lainnya. + * Pada dasarnya, kode yang mencetak sebuah peringatan pada Ruby 2.7 tidak akan +bekerja. Lihat [dokumen](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) untuk detail. + * Omong-omong, *argument forwarding* sekarang mendukung *leading argument*. + + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` + +* Fitur `$SAFE` telah dihilangkan; sekarang adalah sebuah variabel global. + +* Urutan dari *backtrace* telah dibalik pada Ruby 2.5, tetapi itu dibatalkan. Sekarang urutan berperilaku seperti Ruby 2.4; pesan *error* dan nomor baris di mana *exception* terjadi dicetak terlebih dahulu dan pemanggilnya baru dicetak kemudian. + +* Beberapa pustaka standar yang diperbarui. + * RubyGems 3.2.0.rc.1 + * Bundler 2.2.0.rc.1 + * IRB 1.2.6 + * Reline 0.1.5 + +* Berikut adalah pustaka yang tidak lagi masuk sebagai *bundled gem*. + Pasang *gem* berikut jika ingin menggunakan fiturnya. + * net-telnet + * xmlrpc + +* Memindahkan *default gem* ke *bundled gem*. + * rexml + * rss + +* Memindahkan *stdlib* ke *default gem*. Berikut adalah *default gem* yang telah dipublikasikan ke rubygems.org + * abbrev + * base64 + * English + * erb + * find + * io-nonblock + * io-wait + * net-ftp + * net-http + * net-imap + * net-protocol + * nkf + * open-uri + * optparse + * resolv + * resolv-replace + * rinda + * securerandom + * set + * shellwords + * tempfile + * time + * tmpdir + * tsort + * weakref + +Lihat [NEWS](https://github.com/ruby/ruby/blob/v3_0_0_preview1/NEWS.md) +atau [commit logs](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_preview1) +untuk lebih detail. + +{% assign release = site.data.releases | where: "version", "3.0.0-preview1" | first %} + +Dengan perubahan tersebut, [{{ release.stats.files_changed }} berkas berubah, {{ release.stats.insertions }} sisipan(+), {{ release.stats.deletions }} terhapus(-)](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_preview1) +sejak Ruby 2.7.0! + +Mohon coba Ruby 3.0.0-preview1 dan berikan kami umpan balik! + +## Unduh + +* <{{ release.url.bz2 }}> + + SIZE: {{ release.size.bz2 }} + SHA1: {{ release.sha1.bz2 }} + SHA256: {{ release.sha256.bz2 }} + SHA512: {{ release.sha512.bz2 }} + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Cuplikan 3.0.0-preview2 + +Kami merencanakan untuk memasukkan ["type-profiler"](https://github.com/mame/ruby-type-profiler) +yang mana adalah sebuah fitur analisis *static type*. Nantikan! + +## Apa itu Ruby + +Ruby pertama kali dikembangkan oleh Matz (Yukihiro Matsumoto) pada 1993 +dan sekarang dikembangkan sebagai *Open Source*. Ruby berjalan di berbagai +jenis *platform* dan digunakan di seluruh dunia khususnya pengembangan *web*. From 0034de4fe74cf2536180b3cb367057f84ac0af4d Mon Sep 17 00:00:00 2001 From: Andrias Meisyal Date: Sat, 28 Nov 2020 21:57:45 +0700 Subject: [PATCH 0011/1292] Translate CVE-2020-25613: Potential HTTP Request Smuggling Vulnerability in WEBrick (id) --- ...9-http-request-smuggling-cve-2020-25613.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 id/news/_posts/2020-09-29-http-request-smuggling-cve-2020-25613.md diff --git a/id/news/_posts/2020-09-29-http-request-smuggling-cve-2020-25613.md b/id/news/_posts/2020-09-29-http-request-smuggling-cve-2020-25613.md new file mode 100644 index 0000000000..869d7b20e4 --- /dev/null +++ b/id/news/_posts/2020-09-29-http-request-smuggling-cve-2020-25613.md @@ -0,0 +1,42 @@ +--- +layout: news_post +title: "CVE-2020-25613: Potensi Kerentanan HTTP Request Smuggling pada WEBrick" +author: "mame" +translator: "meisyal" +date: 2020-09-29 06:30:00 +0000 +tags: security +lang: id +--- + +Sebuah potensi kerentanan HTTP *request smuggling* pada WEBrick telah dilaporkan. +Kerentanan ini ditetapkan sebagai penanda CVE +[CVE-2020-25613](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-25613). +Kami sangat merekomendasikan Anda untuk memperbarui *webrick gem*. + +## Detail + +WEBrick sangat toleran terhadap sebuah *Transfer-Encoding header* yang tidak +valid. Hal ini bisa menyebabkan interpretasi yang tidak konsisten antara +WEBrick dan beberapa HTTP *proxy server*, yang memperbolehkan penyerang untuk +"smuggle" sebuah *request*. Lihat +[CWE-444](https://cwe.mitre.org/data/definitions/444.html) untuk lebih detail. + +Mohon perbarui *webrick gem* ke versi 1.6.1 atau setelahnya. Anda dapat +menggunakan `gem update webrick` untuk memperbarui. Jika Anda menggunakan +*bundler*, tambahkan `gem "webrick", ">= 1.6.1"` pada `Gemfile` Anda. + +## Versi terimbas + +* *webrick gem* 1.6.0 atau sebelumnya +* versi *webrick* yang di-*bundle* Ruby 2.7.1 atau sebelumnya +* versi *webrick* yang di-*bundle* Ruby 2.6.6 atau sebelumnya +* versi *webrick* yang di-*bundle* Ruby 2.5.8 atau sebelumnya + +## Rujukan + +Terima kasih kepada [piao](https://hackerone.com/piao) yang telah menemukan +masalah ini. + +## Riwayat + +* Semula dipublikasikan pada 2020-09-29 06:30:00 (UTC) From 4b3713b8dbe6f890765afe4b2ff885629f6560af Mon Sep 17 00:00:00 2001 From: Andrias Meisyal Date: Fri, 4 Dec 2020 23:40:55 +0700 Subject: [PATCH 0012/1292] Translate Ruby 2.7.2 released news (id) --- .../_posts/2020-10-02-ruby-2-7-2-released.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 id/news/_posts/2020-10-02-ruby-2-7-2-released.md diff --git a/id/news/_posts/2020-10-02-ruby-2-7-2-released.md b/id/news/_posts/2020-10-02-ruby-2-7-2-released.md new file mode 100644 index 0000000000..ec498d8d29 --- /dev/null +++ b/id/news/_posts/2020-10-02-ruby-2-7-2-released.md @@ -0,0 +1,61 @@ +--- +layout: news_post +title: "Ruby 2.7.2 Dirilis" +author: "nagachika" +translator: "meisyal" +date: 2020-10-02 11:00:00 +0000 +lang: id +--- + +Ruby 2.7.2 telah dirilis. + +Rilis ini berisi *intentional incompatibility*. Peringatan *deprecation* +dinonaktifkan secara *default* pada 2.7.2 and versi selanjutnya. Anda dapat +mengaktifkan peringatan *deprecation* dengan menambahkan opsi -w atau +-W:deprecated pada *command-line*. Mohon cek topik-topik di bawah ini untuk +lebih detail. + +* [Feature #17000 2.7.2 turns off deprecation warnings by default](https://bugs.ruby-lang.org/issues/17000) +* [Feature #16345 Don't emit deprecation warnings by default.](https://bugs.ruby-lang.org/issues/16345) + +Rilis ini juga berisi versi baru dari *webrick* dengan sebuah perbaikan +keamanan yang dijelaskan pada artikel berikut. + +* [CVE-2020-25613: Potensi Kerentanan HTTP Request Smuggling pada WEBrick](/id/news/2020/09/29/http-request-smuggling-cve-2020-25613/) + +## Unduh + +{% assign release = site.data.releases | where: "version", "2.7.2" | first %} + +* <{{ release.url.bz2 }}> + + SIZE: {{ release.size.bz2 }} + SHA1: {{ release.sha1.bz2 }} + SHA256: {{ release.sha256.bz2 }} + SHA512: {{ release.sha512.bz2 }} + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Komentar Rilis + +Terima kasih kepada *committer*, pengembang, dan pengguna yang telah +menyediakan laporan dan kontribusi sehingga memungkinkan rilis ini. From 649f0f341b9ba2f67c17d5dad0d2a90f1c2145c4 Mon Sep 17 00:00:00 2001 From: Andrias Meisyal Date: Fri, 18 Dec 2020 22:47:30 +0700 Subject: [PATCH 0013/1292] Fix news link to a translated news (id) --- id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md b/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md index a96108a9c0..101a9c246e 100644 --- a/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md +++ b/id/news/_posts/2020-09-25-ruby-3-0-0-preview1-released.md @@ -163,7 +163,7 @@ berubah pada rilis *preview* berikutnya. * *Keyword argument* dipisahkan dari *argument* lainnya. * Pada dasarnya, kode yang mencetak sebuah peringatan pada Ruby 2.7 tidak akan -bekerja. Lihat [dokumen](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) untuk detail. +bekerja. Lihat [dokumen](https://www.ruby-lang.org/id/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) untuk detail. * Omong-omong, *argument forwarding* sekarang mendukung *leading argument*. ``` ruby From d75b6045d6e0098a7e41dab1d26f82e45297ca8a Mon Sep 17 00:00:00 2001 From: "NARUSE, Yui" Date: Mon, 21 Dec 2020 01:03:53 +0900 Subject: [PATCH 0014/1292] Ruby 3.0.0 RC1 Released (#2567) --- _data/downloads.yml | 2 +- _data/releases.yml | 28 ++ .../2020-12-20-ruby-3-0-0-rc1-released.md | 308 ++++++++++++++++++ .../2020-12-20-ruby-3-0-0-rc1-released.md | 285 ++++++++++++++++ 4 files changed, 622 insertions(+), 1 deletion(-) create mode 100644 en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md create mode 100644 ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md diff --git a/_data/downloads.yml b/_data/downloads.yml index 6f321476f9..c8bbbe8244 100644 --- a/_data/downloads.yml +++ b/_data/downloads.yml @@ -4,7 +4,7 @@ # optional preview: - - 3.0.0-preview2 + - 3.0.0-rc1 stable: diff --git a/_data/releases.yml b/_data/releases.yml index 3f2710052a..11f3cd02fa 100644 --- a/_data/releases.yml +++ b/_data/releases.yml @@ -21,6 +21,34 @@ # 3.0 series +- version: 3.0.0-rc1 + date: 2020-12-20 + post: /en/news/2020/12/20/ruby-3-0-0-rc1-released/ + stats: + files_changed: 3889 + insertions: 195560 + deletions: 152740 + url: + gz: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0-rc1.tar.gz + zip: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0-rc1.zip + xz: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0-rc1.tar.xz + size: + gz: 19488885 + zip: 23902334 + xz: 14341128 + sha1: + gz: 34ede2128a90ef3217d9cab9efcdf20fc444f67c + zip: e3e20b4d0ec895e579ae416f2b7552c6be3596f7 + xz: deff34cf67373dca166e9961051b6c4723aaaec6 + sha256: + gz: e1270f38b969ce7b124f0a4c217e33eda643f75c7cb20debc62c17535406e37f + zip: 25ced95fa544af6a64d348dc5eace008edfda22f55ed1f6ad9f932b344e6196d + xz: f1adda082f9291e394d25ed32975abbef90962dc4c8b11130586a0151558e79a + sha512: + gz: 798926db82d27366b39be97556ac5cb322986b96df913c398449bd3ece533e484a3047fe35e7a6241dfbd0f7da803438f5b04b805b33f95c73e3e41d0bb51183 + zip: c81b3bf7ce582bf39fd7bc1e691d0777ed4cf38ca6b4d54bc9edaef076ae8bcecb6a86ebfd773591f7d8533e772517033c762d35fdc8b05cb4db4488c2bacec2 + xz: f4f13dbfa1c96088eb3dbfba0cb1fe99f4e17197ee2d4b78fbe16496780797a10daa3f2ff9c38d2d7b316974101eccf45184708ad05491fb49898b3a7cc6d673 + - version: 3.0.0-preview2 date: 2020-12-08 post: /en/news/2020/12/08/ruby-3-0-0-preview2-released/ diff --git a/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md new file mode 100644 index 0000000000..5f8424309c --- /dev/null +++ b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -0,0 +1,308 @@ +--- +layout: news_post +title: "Ruby 3.0.0 RC1 Released" +author: "naruse" +translator: +date: 2020-12-20 00:00:00 +0000 +lang: en +--- + +We are pleased to announce the release of Ruby 3.0.0-rc1. + +It introduces a number of new features and performance improvements. + +## Static Analysis + +### RBS + +RBS is a language to describe the types of Ruby programs. + +Type checkers including TypeProf and other tools supporting RBS will understand Ruby programs much better with RBS definitions. + +You can write down the definition of classes and modules: methods defined in the class, instance variables and their types, and inheritance/mix-in relations. + +The goal of RBS is to support commonly seen patterns in Ruby programs and it allows writing advanced types including union types, method overloading, and generics. It also supports duck typing with _interface types_. + +Ruby 3.0 ships with `rbs` gem, which allows parsing and processing type definitions written in RBS. +The following is a small example of RBS with class, module, and constant definitions. + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|` means union types, `User` or `Bot`. + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # Method overloading is supported. + | (File, from: User | Bot) -> Message + end +end +``` + +See [README of rbs gem](https://github.com/ruby/rbs) for more detail. + +### TypeProf + +TypeProf is a type analysis tool bundled in the Ruby package. + +Currently, TypeProf serves as a kind of type inference. + +It reads plain (non-type-annotated) Ruby code, analyzes what methods are defined and how they are used, and generates a prototype of type signature in RBS format. + +Here is a simple demo of TypeProf. + +An example input: + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +An example output: + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +You can run TypeProf by saving the input as "test.rb" and invoke a command called "typeprof test.rb". + +You can also [try TypeProf online](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=). (It runs TypeProf on the server side, so sorry if it is out!) + +See [the documentation](https://github.com/ruby/typeprof/blob/master/doc/doc.md) and [demos](https://github.com/ruby/typeprof/blob/master/doc/demo.md) for details. + +TypeProf is experimental and not so mature yet; only a subset of the Ruby language is supported, and the detection of type errors is limited. But it is still growing rapidly to improve the coverage of language features, the analysis performance, and usability. Any feedback is very welcome. + +## Ractor (experimental) +Ractor is an Actor-model like concurrent abstraction designed to provide a parallel execution feature without thread-safety concerns. + +You can make multiple ractors and you can run them in parallel. Ractor enables you to make thread-safe parallel programs because ractors can not share normal objects. Communication between ractors are supported by message passing. + +To limit sharing of objects, Ractor introduces several restrictions to the Ruby's syntax (without multiple Ractors, there is no restriction). + +The specification and implementation are not matured and may be changed in the future, so this feature is marked as experimental and show the "experimental feature" warning when the first `Ractor.new`. + +The following small program calculates `n.prime?` (`n` is relatively a big integer) in parallel with two ractors. You will confirm that the program execution is about x2 times faster compared to the sequential program on the parallel computer. + +``` ruby +require 'prime' +# n.prime? with sent integers in r1, r2 run in parallel +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.recv + n.prime? + end +end +# send parameters +r1.send 2**61 - 1 +r2.send 2**61 + 15 +# wait for the results of expr1, expr2 +p r1.take #=> true +p r2.take #=> true +``` + +See [doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md) for more details. + +## Fiber Scheduler + +`Fiber#scheduler` is introduced for intercepting blocking operations. This allows for light-weight concurrency without changing existing code. Watch ["Don't Wait For Me, Scalable Concurrency for Ruby 3"](https://www.youtube.com/watch?v=Y29SSOS4UOc) for an overview of how it works. + +Currently supported classes/methods: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` and related methods (e.g. `#wait_readable`, `#gets`, `#puts` and so on). +- `IO#select` is *not supported*. + +(Explain Async gem with links). This example program will perform several HTTP requests concurrently: + +(Explain this:) +1. async is outer gem +2. async uses this new feature + +``` ruby +require 'async' +require 'net/http' +require 'uri' +Async do + ["ruby", "python", "c"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + +## Other Notable New Features + +* One-line pattern matching is redesigned. (experimental) + * `=>` is added. It can be used as like rightward assignment. + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` + * `in` is changed to return `true` or `false`. + + ```ruby + # version 3.0 + 0 in 1 #=> false + + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` + +* Find pattern is added. (experimental) + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` +* Endless method definition is added. + ``` ruby + def square(x) = x * x + ``` +* `Hash#except` is now built-in. + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` +* Memory view is added as an experimental feature + * This is a new C-API set to exchange a raw memory area, such as a numeric array and a bitmap image, between extension libraries. The extension libraries can share also the metadata of the memory area that consists of the shape, the element format, and so on. Using these kinds of metadata, the extension libraries can share even a multidimensional array appropriately. This feature is designed by referring to Python's buffer protocol. + +## Performance improvements + +* Many improvements were implemented in MJIT. See NEWS in detail. +* Pasting long code to IRB is 53 times faster than bundled with Ruby 2.7.0. For example, the time required to paste [this sample code](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) goes from 11.7 seconds to 0.22 seconds. + +## Other notable changes since 2.7 + +* Keyword arguments are separated from other arguments. + * In principle, code that prints a warning on Ruby 2.7 won't work. See the [document](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) in detail. + * By the way, arguments forwarding now supports leading arguments. + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` +* Pattern matching (`case/in`) is no longer experimental. +* The `$SAFE` feature was completely removed; now it is a normal global variable. +* The order of backtrace had been reversed at Ruby 2.5, and is reverted. Now it behaves like Ruby 2.4; an error message and the line number where the exception occurs are printed first, and its callers are printed later. +* Some standard libraries are updated. + * RubyGems 3.2.2 + * Bundler 2.2.2 + * IRB 1.2.6 + * Reline 0.1.5 + * Pysch 3.2.1 + * JSON 2.4.1 + * BigDecimal 3.0.0 + * CSV 3.1.9 + * Digest 3.0.0 + * Fiddle 1.0.4 + * StringIO 3.0.0 + * StringScanner 3.0.0 +* The following libraries are no longer bundled gems. + Install the corresponding gems to use these features. + * net-telnet + * xmlrpc +* The following default gems are now bundled gems. + * rexml + * rss +* The following stdlib files are now default gems and are published on rubygems.org. + * English + * abbrev + * base64 + * drb + * debug + * erb + * find + * net-ftp + * net-http + * net-imap + * net-protocol + * open-uri + * optparse + * pp + * prettyprint + * resolv-replace + * resolv + * rinda + * set + * securerandom + * shellwords + * tempfile + * tmpdir + * time + * tsort + * un + * weakref + * digest + * io-nonblock + * io-wait + * nkf + * pathname + * syslog + * win32ole + +See [NEWS](https://github.com/ruby/ruby/blob/v3_0_0_rc1/NEWS.md) +or [commit logs](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_rc1) +for more details. + +{% assign release = site.data.releases | where: "version", "3.0.0-rc1" | first %} + +With those changes, [{{ release.stats.files_changed }} files changed, {{ release.stats.insertions }} insertions(+), {{ release.stats.deletions }} deletions(-)](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0) +since Ruby 2.7.0! + +Please try Ruby 3.0.0-rc1, and give us any feedback! + +## Download + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## What is Ruby + +Ruby was first developed by Matz (Yukihiro Matsumoto) in 1993, +and is now developed as Open Source. It runs on multiple platforms +and is used all over the world especially for web development. diff --git a/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md new file mode 100644 index 0000000000..3e69eac879 --- /dev/null +++ b/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -0,0 +1,285 @@ +--- +layout: news_post +title: "Ruby 3.0.0 RC1 リリース" +author: "naruse" +translator: +date: 2020-12-20 00:00:00 +0000 +lang: ja +--- + +Ruby 3.0に向けてフィードバックを得るためのリリースである、Ruby 3.0.0-rc1が公開されました。 + +Ruby 3.0には、多くの新しい機能やパフォーマンスの改善が含まれます。 その一部を以下に紹介します。 + +## 静的解析 + +### RBS + +RBSはRubyプログラムの型を記述するための言語です。 + +TypeProfなどの型検査ツールを初めとする静的解析を行うツールは、RBSを利用することでRubyプログラムをより精度良く解析することができます。 + +RBSでは、Rubyプログラムのクラスやモジュールの型を定義します。メソッドやインスタンス変数、定数とその型、継承やmixinなどの関係などが記述できます。 + +RBSはRubyプログラムに頻出するパターンをサポートするように設計されており、ユニオン型、メソッドオーバーロード、ジェネリクスなどの機能を提供します。さらに「インタフェース型」によってダックタイピングをサポートします。 + +Ruby 3.0には、このRBS言語で書かれた型定義を処理するためのライブラリである `rbs` gemが同梱されています。 + +クラスやモジュール、定数を定義する、簡単なRBSの例を示します。 + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|` は `User` か `Bot` のインスタンスを表現する「ユニオン型」です + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # メソッドオーバーロードを記述することもできます + | (File, from: User | Bot) -> Message + end +end +``` + +詳細については、[rbs gemのREADME](https://github.com/ruby/rbs)を参照してください。 + +### TypeProf + +TypeProf は Ruby パッケージに同梱された型解析ツールです。 + +TypeProf の現在の主な用途は一種の型推論です。 + +型注釈の無い普通の Ruby コードを入力し、どんなメソッドが定義されどのように使われているかを解析し、型シグネチャのプロトタイプを RBS フォーマットで生成します。 + +次は TypeProf の簡単なデモです。 + +サンプル入力 + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +サンプル出力 + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +サンプル入力を"test.rb"という名前で保存し、`typeprof test.rb`というコマンドで TypeProf の解析ができます。 + +[TypeProf をオンラインで試す](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=)こともできます(サーバサイドで TypeProf を動かしているので、サーバが落ちたらごめんなさい)。 + +詳しくは[ドキュメント](https://github.com/ruby/typeprof/blob/master/doc/doc.md)や[デモ](https://github.com/ruby/typeprof/blob/master/doc/demo.md)を見てください。 + +残念ながら TypeProf はまだ実験的で、あまり完成度は高くありません。Ruby 言語のサブセットだけがサポートされていて、型エラー検出の機能は限定的です。ですがいま急速に改良中であり、言語機能のカバレッジ増強、解析効率の向上、利便性の向上などを行っています。フィードバックを歓迎します。 + +## Ractor (experimental) + +Ractor はアクターモデル風の並行・並列制御機構であり、スレッド安全に関する懸念なく、Rubyで並列処理を行うための機能として設計されています。 + +複数のRactorを作成すると、それらは並列計算機上で並列に実行されます。Ractor間では、ほとんどのオブジェクトが共有できないように設計されているため、スレッド安全なプログラムにすることができます。メッセージの送受信により、Ractor間のコミュニケーションを行うことが可能です。 + +Ractor間でのオブジェクトの共有を制限するために、複数Ractorでの実行時には、いくつかのRubyの機能に制限が入ります(ただし、複数のRactorを用いない場合には、これまでのRubyと何も変わりません)。 + +Ractorの仕様と実装は、まだ発展途上であるため、実験的機能として提供されます。初回のRactorの生成時には実験的機能であることが警告で表示されます。 + +次の小さなプログラムでは、二つのRactorを用いて`n.prime?`(`n`は比較的大きな値)の計算を並列に実行します。動かしてみると、逐次実行にくらべて、2コア以上の計算機で計算時間が半分程度になることが確認できます。 + +``` ruby +require 'prime' +# n.prime? with sent integers in r1, r2 run in parallel +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.receive + n.prime? + end +end +# send parameters +r1.send 2**61 - 1 +r2.send 2**61 + 15 +# wait for the results of expr1, expr2 +p r1.take #=> true +p r2.take #=> true +``` + +より詳細は、[doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md) をご覧ください。 + +## Scheduler (experimental) + +`Thread#scheduler` is introduced for intercepting blocking operations. This allows for light-weight concurrency without changing existing code. Watch ["Don't Wait For Me, Scalable Concurrency for Ruby 3"](https://www.youtube.com/watch?v=Y29SSOS4UOc) for an overview of how it works. +Currently supported classes/methods: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `IO#wait`, `IO#read`, `IO#write` and related methods (e.g. `#wait_readable`, `#gets`, `#puts` and so on). +- `IO#select` is *not supported*. + +The current entry point for concurrency is `Fiber.schedule{...}` however this is subject to change by the time Ruby 3 is released. + +Currently, there is a test scheduler available in [`Async::Scheduler`](https://github.com/socketry/async/pull/56). See [`doc/scheduler.md`](https://github.com/ruby/ruby/blob/master/doc/scheduler.md) for more details. + +## その他の主要な新機能 + +* 1行パターンマッチが再設計されました。 (experimental) + * `=>` を新たに使うようになりました。右代入のように使うことができます。 + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` + * `in` は `true` または `false` を返すようになりました。 + + ```ruby + # version 3.0 + 0 in 1 #=> false + + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` +* findパターンが追加されました。 (experimental) + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* 一行メソッド定義が書けるようになりました。 + ``` ruby + def square(x) = x * x + ``` + +* `Hash#except` が組み込みになりました。 + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` +## パフォーマンスの改善 + +* MJITに多数の改善が行われています。詳細はNEWSを参照してください。 +* IRB への長いコードの貼り付けは、Ruby 2.7.0 にバンドルされているものと比較して 53 倍の速さになります。例えば、[このサンプルコード](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b)の貼り付けに要する時間は、11.7 秒から 0.22 秒になります。 + +## その他の注目すべき 2.7 からの変更点 + +* キーワード引数が通常の引数から分離されました。 + * 原則として、2.7 で警告の出ていたコードは動かなくなります。詳細は[別ドキュメント](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/)を参照してください。 + * 関連して、引数のフォワーディングの記法で先頭に引数を書けるようになりました。 + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` +* パターンマッチ(`case/in`)が実験的な機能ではなくなりました。 +* `$SAFE` の機能が完全に削除され、ただのグローバル変数となりました。 +* バックトレースの順序は2.5で逆転しましたが、3.0ではこれを取りやめることになりました。例外が起きた行が先に表示され、呼び出し元が後に表示されるように戻ります。 +* いくつかの標準ライブラリがアップデートされました。 + * RubyGems 3.2.2 + * Bundler 2.2.2 + * IRB 1.2.6 + * Reline 0.1.5 + * Pysch 3.2.1 + * JSON 2.4.1 + * BigDecimal 3.0.0 + * CSV 3.1.9 + * Digest 3.0.0 + * Fiddle 1.0.4 + * StringIO 3.0.0 + * StringScanner 3.0.0 +* 以下のライブラリは標準添付ライブラリから削除されました。3.0 以降で使いたい場合は rubygems から利用してください。 + * net-telnet + * xmlrpc +* 以下のライブラリが新たに bundled gems になりました。Bundler から利用する場合は Gemfile に明示的に指定してください。 + * rexml + * rss +* 以下のライブラリが新たに default gems になりました。rubygems.org からアップデート可能です。 + * English + * abbrev + * base64 + * drb + * debug + * erb + * find + * net-ftp + * net-http + * net-imap + * net-protocol + * open-uri + * optparse + * pp + * prettyprint + * resolv-replace + * resolv + * rinda + * set + * securerandom + * shellwords + * tempfile + * tmpdir + * time + * tsort + * un + * weakref + * digest + * io-nonblock + * io-wait + * nkf + * pathname + * syslog + * win32ole + +その他詳細については、[NEWS](https://github.com/ruby/ruby/blob/v3_0_0_rc1/NEWS.md) ファイルまたは[コミットログ](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_rc1)を参照してください。 + +{% assign release = site.data.releases | where: "version", "3.0.0-rc1" | first %} + +なお、こうした変更により、Ruby 2.7.0 以降では [{{ release.stats.files_changed }} 個のファイルに変更が加えられ、{{ release.stats.insertions }} 行の追加と {{ release.stats.deletions }} 行の削除が行われました](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0) ! + +ぜひ Ruby 3.0.0-rc1 を試して、フィードバックをお願いします! + +## ダウンロード + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Ruby とは + +Rubyはまつもとゆきひろ (Matz) によって1993年に開発が始められ、今もオープンソースソフトウェアとして開発が続けられています。Rubyは様々なプラットフォームで動き、世界中で、特にWebアプリケーション開発のために使われています。 From 0e22e3de5c74a55ce7b8ca5f06634ab3a1b47364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20T=C3=A1mara=20Pati=C3=B1o?= Date: Sun, 20 Dec 2020 12:01:53 -0500 Subject: [PATCH 0015/1292] Translate Ruby 3.0.0-preview2 released (es) (#2568) * Translate Ruby 3.0.0-previe2 released (es) --- ...2020-12-08-ruby-3-0-0-preview2-released.md | 366 ++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 es/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md diff --git a/es/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md b/es/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md new file mode 100644 index 0000000000..9329ac757c --- /dev/null +++ b/es/news/_posts/2020-12-08-ruby-3-0-0-preview2-released.md @@ -0,0 +1,366 @@ +--- +layout: news_post +title: "Publicado Ruby 3.0.0 versión previa 2" +author: "naruse" +translator: vtamara +date: 2020-12-08 00:00:00 +0000 +lang: es +--- + +Nos complace anunciar la publicación de Ruby 3.0.0-preview2. + +Introduce una serie de características nuevas y mejoras en +desempeño. + +## Análisis Estático + +###RBS + +RBS es un lenguaje para describir los tipos de los programas Ruby. + +Los verificadores de tipos, incluyendo TypeProf y otras herramientas +que soporten RBS entenderán mejor los programas Ruby con definiciones RBS. + +Usted puede escribir la definición de clases y módulos: métodos que se +definen en la clase, variables de instancia y sus tipos, y relaciones +herencia/mix-in. + +El objetivo de RBS es soportar los patrones que comúnmente se ven +en programas en Ruby y permitir escribir tipos avanzados incluyendo +tipos unión, sobrecarga de métodos y genéricos. También soporta tipado +pato (duck typing) con _tipos de interfaz_. + +Ruby 3.0 se distribuye con la gema `rbs`, que permite analizar +y procesar definiciones de tipos escritas en RBS. +El siguiente es un pequeño ejemplo de RBS con una clase, un modulo y +definiciones de constantes. + +``` rbs +module AplicacionMensajeria + VERSION: String + class Channel + attr_reader nombre: String + attr_reader mensajes: Array[Mensaje] + attr_reader usuarios: Array[Usuario | Robot] # `|` significa tipos unión, `Usuario` o `Robot`. + + def initialize: (String) -> void + + def publicar: (String, de: Usuario | Robot) -> Mensaje # Se soporta sobrecarga de métodos. + | (File, de: Usuaurio | Robot) -> Mensaje + end +end +``` + +Ver más detalles en el +[archivo README de la gema rbs](https://github.com/ruby/rbs). + + +### TypeProf + +TypeProf es una herramienta para análisis de tipos incluida en el paquete +Ruby. + +Actualmente, TypeProf sirve como una forma de inferencia de tipos. + +Lee código Ruby plano (sin anotiaciones de tipos), analiza que métodos se +definen y como se usan, y genera un prototipo de la firma de los tipos en +formato RBS. + +Aquí hay una simple demostración de TypeProf. + +Entrada de ejemplo: + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +Salida de ejemplo: + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +Puede ejecutar TypeProf guardando el archivo de entrada como "test.rb" y +ejecutandolo como "typeprof test.rb". + +También puede [probar TypeProf en línea](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=). (TypeProf corre al lado del servidor, así que ¡disculpe si no está operando!) + +Ver detalles en [la documentación](https://github.com/ruby/typeprof/blob/master/doc/doc.md) y en [demostraciones](https://github.com/ruby/typeprof/blob/master/doc/demo.md). + +TypeProf es experimental y aún no es una herramienta madura, sólo soporta un +subconjunto del lenguaje Ruby, y la detección de errores en tipos es limitada. +Pero está creciendo rapidamente para mejorar la cobertura de las +características del lenguaje, el desempeño del análisis y la usabilidad. +Toda retroalimentación es bienvenida. + +## Ractor (experimental) + +Un Ractor es una abstracción de concurrencia al estilo Actor-modelo, +diseñada para brindar una forma de ejecución en paralelo sin +preocuparse por la seguridad de los hilos (thread-safe) de ejecución. + +Puede crear múltiples ractors y puede ejecutarlos en paralelo. +Un Ractor permite hacer programas paralelos con seguridad en los hilos +de ejecución porque los ractors no comparten objetos normales. +La comunicación entre ractors se soporta mediante envío de +mensajes. + +Para limitar los objetos que se comparten, Ractor introduce diversas +restricciones a la sintaxis de Ruby (no hay cambio cuando no hay múltiples +Ractors). + +La especificación e implementación no es madura y podría cambiar a +futuro, por eso esta característica se señala como experimental +y con el primer `Ractor.new` se presenta una advertencia de característica +experimental. + +El siguiente programita calcula `prime?` en paralelo con dos +ractores. Podrá comprobar que la ejecución es casi 2 veces más rápida +que la del programa secuencial en un computador paralelo. + +``` ruby +require 'prime' + +# n.prime? con enteros enviados en r1, r2 que corren en paralelo +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.recv + n.prime? + end +end + +# enviar parámetros +r1.send 2**61 - 1 +r2.send 2**61 + 15 + +# esperar resultados de expr1 y expr2 +p r1.take #=> true +p r2.take #=> true +``` + +Ver más detalles en +[doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md). + + +## Planificador (__Scheduler__) de Fibras + +Se introduce `Fiber#scheduler` para interceptar operaciones que bloquean. +Esto permite una concurrencia liviana sin cambiar el +código existente. Dar un vistazo general y ver como funciona en ["Don't Wait For Me, Scalable Concurrency for Ruby 3"](https://www.youtube.com/watch?v=Y29SSOS4UOc). + +Los métodos y clases que se soportan en el momento son: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` y métodos relacionados (e.g. + `#wait_readable`, `#gets`, `#puts` y así sucesivamente). +- `IO#select` *no es soportado*. + +El actual punto de entrada para la concurrencia es +`Fiber.schedule{...}` sin embargo está sujeto a cambios para +cuando se publique Ruby 3. + +(Explicar la gema Async con enlaces). Este programa de ejemplo realizará +varias peticiones HTTP de manera concurrente: +(Explicar esto:) +1. async es una gema exterior +2. async usa esta nueva característica + +``` ruby +require 'async' +require 'net/http' +require 'uri' +Async do + ["ruby", "python", "c"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + + +## Otras características notables + +* El reconocimiento de patrones en una línea ahora usa `=>` en lugar + de `in`. + + ``` ruby + # version 3.0 + {a: 0, b: 1} => {a:} + p a # => 0 + # version 2.7 + {a: 0, b: 1} in {a:} + p a # => 0 + ``` + +* Se agrega un patrón Encontrar (__Find__). + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* Se agrega una definición de métodos que no requiere `end`. + + ``` ruby + def cuadrado(x) = x * x + ``` + +* `Hash#except` ahora es un método incorporado. + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + +* __Memory view__ se agrega como característica experimental + + * Este es un nuevo conjunto de llamados en la API de C para intercambiar + áreas de memoria puras entre las librerías que son extensiones, por + ejemplo para intercambiar un arreglo numérico con un mapa de bits. + Las librerías que son extensiones pueden compartir también los + metadatos del área de memoria que constan de la forma, el formato del + elemento y así sucesivamente. Usando esta clase de metadatos, las + librerías que son extensiones pueden compartir apropiadamente incluso un + arreglo multidimensional. Esta nueva característica se diseñó empleando + como referencia el protocolo de colchón (__buffer__ ) de Python. + +## Mejoras en desempeño + +* Se implemetaron muchas mejoras en MJIT. Ver detalles en el archivo + NEWS. +* Pegar código largo en IRB es 53 veces más rápido que con Ruby 2.7.0. + Por ejemplo el tiempo requerido para pegar [este código de ejemplo](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) + pasa de 11.7 segundos a 0.22 segundos. + + +## Otros cambios notables desde 2.7 + +* Los argumentos de palabra clave se separan de otros argumentos. + * En principio, el código que presente una advertencia en Ruby 2.7 no + funcionará. Ver detalles en + [este documento](https://www.ruby-lang.org/es/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/). + * Por cierto, el re-envío de argumentos ahora soporta argumentos principales. + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` + +* La característica `$SAFE` se eliminó por completo; ahora es una variable + global normal. + +* El orden de la traza de llamados (__backtrace__) se había invertido + en Ruby 2.5, pero esto se ha revertido. Ahora se comporta como + Ruby 2.4; se imprime primero un mensaje de error y el número de línea donde + ocurrió la excepción; las funciones que había hecho la llamada se imprimen + después. + +* Se actualizaron algunas librerías estándar. + * RubyGems 3.2.0.rc.1 + * Bundler 2.2.0.rc.1 + * IRB 1.2.6 + * Reline 0.1.5 + +* Las siguientes librerías ya no son gemas distribuidas con Ruby. + Instale las gemas correspondientes para usar sus funcionalidades. + * net-telnet + * xmlrpc + +* Las siguientes gemas por omisión se volvieron gemas distribuidas + con Ruby. + * rexml + * rss + +* Los siguientes archivos de stdlib ahora son gemas y se publicaron en + rubygems.org. + * abbrev + * base64 + * English + * erb + * find + * io-nonblock + * io-wait + * net-ftp + * net-http + * net-imap + * net-protocol + * nkf + * open-uri + * optparse + * resolv + * resolv-replace + * rinda + * securerandom + * set + * shellwords + * tempfile + * time + * tmpdir + * tsort + * weakref + +Ver más detalles en el archivo +[NEWS](https://github.com/ruby/ruby/blob/v3_0_0_preview2/NEWS.md) +o [en la bitácora de contribuciones](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_preview2). + +{% assign release = site.data.releases | where: "version", "3.0.0-preview2" | first %} + +Con estos cambios, [{{ release.stats.files_changed }} archivos cambiados, {{ release.stats.insertions }} inserciones(+), {{ release.stats.deletions }} eliminaciones(-)](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0) +desde Ruby 2.7.0! + +¡Por favor pruebe Ruby 3.0.0-preview2, y denos cualquier retroalimentación! + +## Descargas + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + + +## Qué es Ruby + +Ruby fue desarrollado inicialmente por Matz (Yukihiro Matsumoto) en 1993, +y ahora es desarrollado como código abierto. Corre en muchas +plataformas y se usa en todas partes del mundo especialmente para +desarrollos web. From 259ef2901f83c8f0442c30a6ad303c06d977d914 Mon Sep 17 00:00:00 2001 From: Marcus Stollsteimer Date: Mon, 21 Dec 2020 22:31:14 +0100 Subject: [PATCH 0016/1292] Update rouge to 3.25.0 Remove restriction to rouge < 3.24.0 and update rouge. The bug in rouge 3.24.0 concerning syntax highlighting of regular expressions has been fixed in version 3.25.0, see * https://github.com/rouge-ruby/rouge/issues/1618 * https://github.com/rouge-ruby/rouge/pull/1624 --- Gemfile | 2 +- Gemfile.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Gemfile b/Gemfile index 86d3d10afa..43685579d2 100644 --- a/Gemfile +++ b/Gemfile @@ -4,7 +4,7 @@ ruby "~> 2.7.2" gem "rake" gem "jekyll", "~> 4.0" -gem "rouge", "< 3.24.0" +gem "rouge" gem "unicorn" gem "lanyon" diff --git a/Gemfile.lock b/Gemfile.lock index 8e9a4b977c..ad86aa304c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -68,7 +68,7 @@ GEM rb-inotify (0.10.1) ffi (~> 1.0) rexml (3.2.4) - rouge (3.23.0) + rouge (3.25.0) safe_yaml (1.0.5) sassc (2.4.0) ffi (~> 1.9) @@ -106,7 +106,7 @@ DEPENDENCIES rack-rewrite rack-ssl rake - rouge (< 3.24.0) + rouge spidr (~> 0.6) unicorn validate-website (~> 1.6) From a8abc9c499da32ba12e7e295323017d5aee430e4 Mon Sep 17 00:00:00 2001 From: Marcus Stollsteimer Date: Mon, 21 Dec 2020 23:17:27 +0100 Subject: [PATCH 0017/1292] Fix wrong indentation of code blocks in 3.0.0-rc1 post Indenting the code blocks too much causes surplus leading spaces on the rendered page. --- .../2020-12-20-ruby-3-0-0-rc1-released.md | 68 ++++++++++------- .../2020-12-20-ruby-3-0-0-rc1-released.md | 73 +++++++++++-------- 2 files changed, 81 insertions(+), 60 deletions(-) diff --git a/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md index 5f8424309c..f04fb8490b 100644 --- a/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md +++ b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -86,6 +86,7 @@ See [the documentation](https://github.com/ruby/typeprof/blob/master/doc/doc.md) TypeProf is experimental and not so mature yet; only a subset of the Ruby language is supported, and the detection of type errors is limited. But it is still growing rapidly to improve the coverage of language features, the analysis performance, and usability. Any feedback is very welcome. ## Ractor (experimental) + Ractor is an Actor-model like concurrent abstraction designed to provide a parallel execution feature without thread-safety concerns. You can make multiple ractors and you can run them in parallel. Ractor enables you to make thread-safe parallel programs because ractors can not share normal objects. Communication between ractors are supported by message passing. @@ -152,45 +153,54 @@ end ## Other Notable New Features * One-line pattern matching is redesigned. (experimental) + * `=>` is added. It can be used as like rightward assignment. - ```ruby - 0 => a - p a #=> 0 + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` - {b: 0, c: 1} => {b:} - p b #=> 0 - ``` * `in` is changed to return `true` or `false`. - ```ruby - # version 3.0 - 0 in 1 #=> false + ```ruby + # version 3.0 + 0 in 1 #=> false - # version 2.7 - 0 in 1 #=> raise NoMatchingPatternError - ``` + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` * Find pattern is added. (experimental) - ``` ruby - case ["a", 1, "b", "c", 2, "d", "e", "f", 3] - in [*pre, String => x, String => y, *post] - p pre #=> ["a", 1] - p x #=> "b" - p y #=> "c" - p post #=> [2, "d", "e", "f", 3] - end - ``` + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + * Endless method definition is added. - ``` ruby - def square(x) = x * x - ``` + + ``` ruby + def square(x) = x * x + ``` + * `Hash#except` is now built-in. - ``` ruby - h = { a: 1, b: 2, c: 3 } - p h.except(:a) #=> {:b=>2, :c=>3} - ``` + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + * Memory view is added as an experimental feature + * This is a new C-API set to exchange a raw memory area, such as a numeric array and a bitmap image, between extension libraries. The extension libraries can share also the metadata of the memory area that consists of the shape, the element format, and so on. Using these kinds of metadata, the extension libraries can share even a multidimensional array appropriately. This feature is designed by referring to Python's buffer protocol. ## Performance improvements @@ -203,11 +213,13 @@ end * Keyword arguments are separated from other arguments. * In principle, code that prints a warning on Ruby 2.7 won't work. See the [document](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) in detail. * By the way, arguments forwarding now supports leading arguments. + ``` ruby def method_missing(meth, ...) send(:"do_#{ meth }", ...) end ``` + * Pattern matching (`case/in`) is no longer experimental. * The `$SAFE` feature was completely removed; now it is a normal global variable. * The order of backtrace had been reversed at Ruby 2.5, and is reverted. Now it behaves like Ruby 2.4; an error message and the line number where the exception occurs are printed first, and its callers are printed later. diff --git a/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md index 3e69eac879..8a38c91b0c 100644 --- a/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md +++ b/ja/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -137,45 +137,52 @@ Currently, there is a test scheduler available in [`Async::Scheduler`](https://g ## その他の主要な新機能 * 1行パターンマッチが再設計されました。 (experimental) - * `=>` を新たに使うようになりました。右代入のように使うことができます。 - ```ruby - 0 => a - p a #=> 0 + * `=>` を新たに使うようになりました。右代入のように使うことができます。 + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` - {b: 0, c: 1} => {b:} - p b #=> 0 - ``` * `in` は `true` または `false` を返すようになりました。 - ```ruby - # version 3.0 - 0 in 1 #=> false + ```ruby + # version 3.0 + 0 in 1 #=> false + + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` - # version 2.7 - 0 in 1 #=> raise NoMatchingPatternError - ``` * findパターンが追加されました。 (experimental) - ``` ruby - case ["a", 1, "b", "c", 2, "d", "e", "f", 3] - in [*pre, String => x, String => y, *post] - p pre #=> ["a", 1] - p x #=> "b" - p y #=> "c" - p post #=> [2, "d", "e", "f", 3] - end - ``` + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` * 一行メソッド定義が書けるようになりました。 - ``` ruby - def square(x) = x * x - ``` + + ``` ruby + def square(x) = x * x + ``` * `Hash#except` が組み込みになりました。 - ``` ruby - h = { a: 1, b: 2, c: 3 } - p h.except(:a) #=> {:b=>2, :c=>3} - ``` + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + ## パフォーマンスの改善 * MJITに多数の改善が行われています。詳細はNEWSを参照してください。 @@ -186,11 +193,13 @@ Currently, there is a test scheduler available in [`Async::Scheduler`](https://g * キーワード引数が通常の引数から分離されました。 * 原則として、2.7 で警告の出ていたコードは動かなくなります。詳細は[別ドキュメント](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/)を参照してください。 * 関連して、引数のフォワーディングの記法で先頭に引数を書けるようになりました。 + ``` ruby - def method_missing(meth, ...) - send(:"do_#{ meth }", ...) - end + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end ``` + * パターンマッチ(`case/in`)が実験的な機能ではなくなりました。 * `$SAFE` の機能が完全に削除され、ただのグローバル変数となりました。 * バックトレースの順序は2.5で逆転しましたが、3.0ではこれを取りやめることになりました。例外が起きた行が先に表示され、呼び出し元が後に表示されるように戻ります。 From e09e0ab45f04af9a647b264f7f6caa31d1af060e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0smail=20Ar=C4=B1l=C4=B1k?= Date: Tue, 22 Dec 2020 08:22:24 +0300 Subject: [PATCH 0018/1292] Translate 3.0.0 RC1 post (tr) (#2571) --- .../2020-12-20-ruby-3-0-0-rc1-released.md | 328 ++++++++++++++++++ 1 file changed, 328 insertions(+) create mode 100644 tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md diff --git a/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md new file mode 100644 index 0000000000..99528740e6 --- /dev/null +++ b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -0,0 +1,328 @@ +--- +layout: news_post +title: "Ruby 3.0.0 RC1 Yayınlandı" +author: "naruse" +translator: "ismailarilik" +date: 2020-12-20 00:00:00 +0000 +lang: tr +--- + +Ruby 3.0.0-rc1'in yayınlandığını duyurmaktan memnuniyet duyuyoruz. + +Bu sürüm birçok yeni özellik ve performans iyileştirmesi içermektedir. + +## Statik Analiz + +### RBS + +RBS, Ruby programlarındaki tipleri tanımlamada kullanılan bir dildir. + +RBS'yi destekleyen tip kontrol edicileri (TypeProf ve diğer araçlar da dahil), RBS tanımlamaları ile birlikte Ruby programlarını çok daha iyi anlayacaklardır. + +RBS ile sınıfların ve modüllerin tanımını yazabilirsiniz: bir sınıfta tanımlanmış metodlar, örnek değişkenleri ve bu değişkenlerin tipleri, ve miras/mix-in ilişkisi. + +RBS'nin amacı Ruby programlarında sıkça görülen desenleri desteklemektir. +RBS, union tiplerinin de dahil olduğu gelişmiş tipleri, metod aşırı yüklemeyi, ve genelleyicileri yazmaya izin verir. +Ayrıca _arayüz tipleri_ ile ördek tiplemesini de destekler. + +Ruby 3.0 `rbs` gem'i ile gelmektedir, bu gem RBS ile yazılmış tip tanımlarını ayrıştırma ve işlemeye izin verir. +Aşağıdaki kod sınıf, modül ve sabit tanımlamalarını içeren, RBS için küçük bir örnektir. + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|`, union tip anlamına gelmektedir, `User` ya da `Bot`. + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # Metod aşırı yükleme destekleniyor. + | (File, from: User | Bot) -> Message + end +end +``` + +Daha fazla ayrıntı için [rbs gem'inin README](https://github.com/ruby/rbs)'sine bakınız. + +### TypeProf + +TypeProf, Ruby ile paketlenmiş bir tip analizi aracıdır. + +Şu anda TypeProf, bir çeşit tip çıkarımı olarak hizmet vermektedir. + +TypeProf, sade (tiplerin belirtilmediği) Ruby kodunu okur, hangi metodların tanımlandığını ve bu metodların nasıl kullanıldığını analiz eder, ve RBS biçiminde prototip bir tip imzası oluşturur. + +İşte basit bir TypeProf demosu. + +Örnek bir girdi: + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +Örnek bir çıktı: + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +TypeProf'u, girdiyi "test.rb" olarak kaydederek ve "typeprof test.rb" komutunu çağırarak çalıştırabilirsiniz. + +Ayrıca [TypeProf'u çevrimiçi deneyebilirsiniz](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=). +(Burası TypeProf'u sunucu tarafında çalıştırır, yani eğer çalışmazsa kusura bakmayın!) + +Ayrıntılar için [belgelendirmeye](https://github.com/ruby/typeprof/blob/master/doc/doc.md) ve [demolara](https://github.com/ruby/typeprof/blob/master/doc/demo.md) bakın. + +TypeProf şu anda deneysel ve oturmuş değil; Ruby'nin sadece bir alt kümesi destekleniyor, ve tip hatalarının tespit edilmesi kısıtlıdır. +Fakat TypeProf, dil özelliklerinin kapsamasını, analiz performansını ve kullanılırlığı hızlıca artırmak için gelişmektedir. +Herhangi bir geri bildirime çok ihtiyacımız var. + +## Ractor (deneysel) + +Ractor, thread güvenliği endişeleri olmadan paralel çalıştırma özelliğini sağlamak için tasarlanan eşzamanlı soyutlama gibi bir aktör-modeldir. + +Birden fazla ractor yapabilirsiniz ve bunları paralelde çalıştırabilirsiniz. +Ractor thread-güvenli paralel programlar yapmanıza izin verir çünkü ractor'lar normal nesneleri paylaşmazlar. +Ractor'lar arasındaki iletişim mesaj geçirme ile desteklenir. + +Nesnelerin paylaşılmasını kısıtlamak için Ractor, Ruby'nin sözdizimine bazı kısıtlamalar getirir (birden fazla Ractor yoksa, değişiklik yoktur). + +Belirtim ve gerçekleme henüz tam oturmamıştır ve ileride değişecektir, bu sebeple bu özellik deneysel olarak işaretlenmiştir ve ilk `Ractor.new`'de "deneysel özellik" uyarısı gösterilir. + +Aşağıdaki küçük program `n.prime?`'ı (`n` nispeten büyük bir tamsayıdır) iki ractor ile paralelde hesaplar. +Bu programın çalışması paralel bilgisayarda ardışık bir programa göre aşağı yukarı 2 kat daha hızlıdır. + +``` ruby +require 'prime' +# r1 ve r2'deki, tamsayıların gönderildiği n.prime? paralelde çalışır +r1, r2 = *(1..2).map do + Ractor.new do + n = Ractor.recv + n.prime? + end +end +# parametreleri gönder +r1.send 2**61 - 1 +r2.send 2**61 + 15 +# 1. ve 2. deyimin sonuçlarını bekle +p r1.take #=> true +p r2.take #=> true +``` + +Daha fazla ayrıntı için [doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md)'ye bakın. + +## Fiber Zamanlayıcı + +`Fiber#scheduler` bloklayan işlemleri kesmek için tanıtılmıştır. +Bu, var olan kodu değiştirmeden hafif eşzamanlılığa izin verir. +Nasıl çalıştığının genel bir bakış için ["Beni Bekleme, Ruby 3'te Ölçeklenebilir Eşzamanlılık"](https://www.youtube.com/watch?v=Y29SSOS4UOc)'ı izleyin. + +Şu anda desteklenen sınıf ve metodlar: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` ve ilişkili metodlar (`#wait_readable`, `#gets`, `#puts`, vb. gibi). +- `IO#select` *desteklenmemektedir*. + +(Async gem'ini bağlantılarla açıkla). +Bu örnek program birden çok HTTP isteğini eşzamanlı olarak gerçekleştirecektir: + +(Bunu açıkla:) +1. async dışsal bir gem +2. async bu yeni özelliği kullanır + +``` ruby +require 'async' +require 'net/http' +require 'uri' +Async do + ["ruby", "python", "c"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + +## Other Notable New Features + +* Tek satır desen eşleştirme yeniden tasarlandı. (deneysel) + * `=>` eklendi. + Sağ taraf ataması olarak kullanılabilir. + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` + * `in`, `true` ya da `false` döndürmesi için değiştirildi. + + ```ruby + # sürüm 3.0 + 0 in 1 #=> false + + # sürüm 2.7 + 0 in 1 #=> NoMatchingPatternError yükseltir + ``` + +* Bulma deseni eklendi. (deneysel) + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* Sonsuz metod tanımı eklendi. + ``` ruby + def square(x) = x * x + ``` +* `Hash#except` şimdi gömülü. + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + +* Hafıza görünümü deneysel bir özellik olarak eklendi. + * Bu, uzantı kütüphaneleri arasında sayısal bir dizi ve bir biteşlem görüntüsü gibi ham bir hafıza alanını takas etmek için yeni bir C-API'ıdır. + Uzantı kütüphaneleri ayrıca şekil, öğe biçimi, vb. içeren hafıza alanlarının üstverilerini de paylaşır. + Bu gibi üstverileri kullanarak, uzantı kütüphaneleri çok boyutlu dizileri bile uygun şekilde paylaşabilirler. + Bu özellik Python'ın tampon protokolüne danışılarak tasarlanmıştır. + +## Performans iyileştirmeleri + +* Birçok geliştirme MJIT'te gerçeklenmiştir. + Ayrıntılar için NEWS'e bakınız. +* Uzun bir kodu IRB'ye yapıştırmak, Ruby 2.7.0'da gelene göre 53 kat daha hızlı. + Örneğin, [şu örnek kodu](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) yapıştırmak için gereken zaman 11.7 saniyeden 0.22 saniyeye düşmüştür. + +## 2.7'den bu yana diğer dikkate değer değişiklikler + +* Anahtar sözcük argümanları diğer argümanlardan ayrılmıştır. + * Prensipte, Ruby 2.7'de bir uyarı yazdıran kod çalışmayacaktır. + Ayrıntılar için [belgeye](https://www.ruby-lang.org/tr/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) bakınız. + * Bu arada argüman yönlendirme artık sondaki argümanları da destekliyor. + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` +* Desen eşleştirme (`case/in`) artık deneysel değil. +* `$SAFE` özelliği tamamiyle silindi; şimdi sadece normal bir global değişken. +* Geriizleme sırası Ruby 2.5'te tersine çevrildi, fakat bu iptal edildi. + Şimdi Ruby 2.4'teki gibi bir davranış söz konusu; hata mesajı ve istisnanın meydana geldiği satır numarası ilk olarak yazdırılır, daha sonra ise çağırıcıları yazdırılır. +* Bazı standart kütüphaneler güncellendi. + * RubyGems 3.2.2 + * Bundler 2.2.2 + * IRB 1.2.6 + * Reline 0.1.5 + * Pysch 3.2.1 + * JSON 2.4.1 + * BigDecimal 3.0.0 + * CSV 3.1.9 + * Digest 3.0.0 + * Fiddle 1.0.4 + * StringIO 3.0.0 + * StringScanner 3.0.0 +* Aşağıdaki kütüphaneler artık paketlenmiyor. + Bu özellikleri kullanmak için denk gelen gem'leri kurun. + * net-telnet + * xmlrpc +* Şu varsayılan gem'ler paketlenmiş gem'ler olarak düzenlendi. + * rexml + * rss +* Aşağıdaki stdlib dosyaları şimdi varsayılan gemler ve rubygems.org'da yayınlandı. + * English + * abbrev + * base64 + * drb + * debug + * erb + * find + * net-ftp + * net-http + * net-imap + * net-protocol + * open-uri + * optparse + * pp + * prettyprint + * resolv-replace + * resolv + * rinda + * set + * securerandom + * shellwords + * tempfile + * tmpdir + * time + * tsort + * un + * weakref + * digest + * io-nonblock + * io-wait + * nkf + * pathname + * syslog + * win32ole + +Daha fazla ayrıntı için [NEWS](https://github.com/ruby/ruby/blob/v3_0_0_rc1/NEWS.md)'e +ya da [işleme loglarına](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0_rc1) +bakın. + +{% assign release = site.data.releases | where: "version", "3.0.0-rc1" | first %} + +Bu değişikliklerle birlikte, 2.7.0'dan bu yana [{{ release.stats.files_changed }} dosya değişti, {{ release.stats.insertions }} ekleme yapıldı(+), {{ release.stats.deletions }} silme yapıldı(-)](https://github.com/ruby/ruby/compare/v2_7_0...v3_0_0)! + +Lütfen Ruby 3.0.0-rc1'i deneyin, ve bize herhangi bir geri bildirim verin! + +## Download + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Ruby nedir + +Ruby ilk olarak Matz (Yukihiro Matsumoto) tarafından 1993'te geliştirilmiştir, ve şu anda Açık Kaynak olarak geliştirilmektedir. +Birçok platformda çalışır ve tüm dünyada genellikle web geliştirmesi için kullanılmaktadır. From 899f2a1d7fc2d0a7cef51950bf9bfb298d593cae Mon Sep 17 00:00:00 2001 From: Marcus Stollsteimer Date: Mon, 21 Dec 2020 23:29:07 +0100 Subject: [PATCH 0019/1292] Update example code in 3.0.0-rc1 post Prefer Ractor::receive over its alias Ractor::recv. --- en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md | 2 +- tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md index f04fb8490b..d6e498f079 100644 --- a/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md +++ b/en/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -102,7 +102,7 @@ require 'prime' # n.prime? with sent integers in r1, r2 run in parallel r1, r2 = *(1..2).map do Ractor.new do - n = Ractor.recv + n = Ractor.receive n.prime? end end diff --git a/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md index 99528740e6..73ed563f95 100644 --- a/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md +++ b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -110,7 +110,7 @@ require 'prime' # r1 ve r2'deki, tamsayıların gönderildiği n.prime? paralelde çalışır r1, r2 = *(1..2).map do Ractor.new do - n = Ractor.recv + n = Ractor.receive n.prime? end end From 031461984539d048f94ef774d2f378efec857426 Mon Sep 17 00:00:00 2001 From: Alexander Ilyin Date: Fri, 25 Dec 2020 02:04:01 +0300 Subject: [PATCH 0020/1292] Fix wrong indentation of code blocks in 3.0.0-rc1 post (tr) See a8abc9c499da32ba12e7e295323017d5aee430e4. --- .../2020-12-20-ruby-3-0-0-rc1-released.md | 65 +++++++++++-------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md index 73ed563f95..4c9f1a0021 100644 --- a/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md +++ b/tr/news/_posts/2020-12-20-ruby-3-0-0-rc1-released.md @@ -164,48 +164,55 @@ end ## Other Notable New Features * Tek satır desen eşleştirme yeniden tasarlandı. (deneysel) + * `=>` eklendi. Sağ taraf ataması olarak kullanılabilir. - ```ruby - 0 => a - p a #=> 0 + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` - {b: 0, c: 1} => {b:} - p b #=> 0 - ``` * `in`, `true` ya da `false` döndürmesi için değiştirildi. - ```ruby - # sürüm 3.0 - 0 in 1 #=> false + ```ruby + # sürüm 3.0 + 0 in 1 #=> false - # sürüm 2.7 - 0 in 1 #=> NoMatchingPatternError yükseltir - ``` + # sürüm 2.7 + 0 in 1 #=> NoMatchingPatternError yükseltir + ``` * Bulma deseni eklendi. (deneysel) - ``` ruby - case ["a", 1, "b", "c", 2, "d", "e", "f", 3] - in [*pre, String => x, String => y, *post] - p pre #=> ["a", 1] - p x #=> "b" - p y #=> "c" - p post #=> [2, "d", "e", "f", 3] - end - ``` + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` * Sonsuz metod tanımı eklendi. - ``` ruby - def square(x) = x * x - ``` + + ``` ruby + def square(x) = x * x + ``` + * `Hash#except` şimdi gömülü. - ``` ruby - h = { a: 1, b: 2, c: 3 } - p h.except(:a) #=> {:b=>2, :c=>3} - ``` + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` * Hafıza görünümü deneysel bir özellik olarak eklendi. + * Bu, uzantı kütüphaneleri arasında sayısal bir dizi ve bir biteşlem görüntüsü gibi ham bir hafıza alanını takas etmek için yeni bir C-API'ıdır. Uzantı kütüphaneleri ayrıca şekil, öğe biçimi, vb. içeren hafıza alanlarının üstverilerini de paylaşır. Bu gibi üstverileri kullanarak, uzantı kütüphaneleri çok boyutlu dizileri bile uygun şekilde paylaşabilirler. @@ -224,11 +231,13 @@ end * Prensipte, Ruby 2.7'de bir uyarı yazdıran kod çalışmayacaktır. Ayrıntılar için [belgeye](https://www.ruby-lang.org/tr/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) bakınız. * Bu arada argüman yönlendirme artık sondaki argümanları da destekliyor. + ``` ruby def method_missing(meth, ...) send(:"do_#{ meth }", ...) end ``` + * Desen eşleştirme (`case/in`) artık deneysel değil. * `$SAFE` özelliği tamamiyle silindi; şimdi sadece normal bir global değişken. * Geriizleme sırası Ruby 2.5'te tersine çevrildi, fakat bu iptal edildi. From 564e08b94b74a64d939fa8163617debdd89e2727 Mon Sep 17 00:00:00 2001 From: "NARUSE, Yui" Date: Fri, 25 Dec 2020 13:25:41 +0900 Subject: [PATCH 0021/1292] Ruby 3.0.0 Released (#2570) * Ruby 3.0.0 Released Co-authored-by: Marcus Stollsteimer --- _data/branches.yml | 4 +- _data/downloads.yml | 2 +- _data/releases.yml | 29 ++ .../_posts/2020-12-25-ruby-3-0-0-released.md | 388 ++++++++++++++++++ .../_posts/2020-12-25-ruby-3-0-0-released.md | 383 +++++++++++++++++ 5 files changed, 803 insertions(+), 3 deletions(-) create mode 100644 en/news/_posts/2020-12-25-ruby-3-0-0-released.md create mode 100644 ja/news/_posts/2020-12-25-ruby-3-0-0-released.md diff --git a/_data/branches.yml b/_data/branches.yml index 8c7d486e4a..a223071472 100644 --- a/_data/branches.yml +++ b/_data/branches.yml @@ -9,8 +9,8 @@ # eol_date: date of EOL (YYYY-MM-DD) - name: 3.0 - status: preview - date: + status: normal maintenance + date: 2020-12-25 eol_date: - name: 2.7 diff --git a/_data/downloads.yml b/_data/downloads.yml index c8bbbe8244..7178265b8f 100644 --- a/_data/downloads.yml +++ b/_data/downloads.yml @@ -4,10 +4,10 @@ # optional preview: - - 3.0.0-rc1 stable: + - 3.0.0 - 2.7.2 - 2.6.6 diff --git a/_data/releases.yml b/_data/releases.yml index 11f3cd02fa..44d17f8954 100644 --- a/_data/releases.yml +++ b/_data/releases.yml @@ -21,6 +21,35 @@ # 3.0 series +- version: 3.0.0 + tag: v3_0_0 + date: 2020-12-25 + post: /en/news/2020/12/25/ruby-3-0-0-released/ + stats: + files_changed: 4028 + insertions: 200058 + deletions: 154063 + url: + gz: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0.tar.gz + zip: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0.zip + xz: https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0.tar.xz + size: + gz: 19539509 + zip: 23862057 + xz: 14374176 + sha1: + gz: 233873708c1ce9fdc295e0ef1c25e64f9b98b062 + zip: 2a9629102d71c7fe7f31a8c91f64e570a40d093c + xz: c142899d70a1326c5a71311b17168f98c15e5d89 + sha256: + gz: a13ed141a1c18eb967aac1e33f4d6ad5f21be1ac543c344e0d6feeee54af8e28 + zip: a5e4fa7dc5434a7259e9a29527eeea2c99eeb5e82708f66bb07731233bc860f4 + xz: 68bfaeef027b6ccd0032504a68ae69721a70e97d921ff328c0c8836c798f6cb1 + sha512: + gz: e62f4f63dc12cff424e8a09adc06477e1fa1ee2a9b2b6e28ca22fd52a211e8b8891c0045d47935014a83f2df2d6fc7c8a4fd87f01e63c585afc5ef753e1dd1c1 + zip: e5bf742309d79f05ec1bd1861106f4b103e4819ca2b92a826423ff451465b49573a917cb893d43a98852435966323e2820a4b9f9377f36cf771b8c658f80fa5b + xz: 2a23c2894e62e24bb20cec6b2a016b66d7df05083668726b6f70af8338211cfec417aa3624290d1f5ccd130f65ee7b52b5db7d428abc4a9460459c9a5dd1a450 + - version: 3.0.0-rc1 date: 2020-12-20 post: /en/news/2020/12/20/ruby-3-0-0-rc1-released/ diff --git a/en/news/_posts/2020-12-25-ruby-3-0-0-released.md b/en/news/_posts/2020-12-25-ruby-3-0-0-released.md new file mode 100644 index 0000000000..2cf09596b4 --- /dev/null +++ b/en/news/_posts/2020-12-25-ruby-3-0-0-released.md @@ -0,0 +1,388 @@ +--- +layout: news_post +title: "Ruby 3.0.0 Released" +author: "naruse" +translator: +date: 2020-12-25 00:00:00 +0000 +lang: en +--- +{% assign release = site.data.releases | where: "version", "3.0.0" | first %} + +We are pleased to announce the release of Ruby {{ release.version }}. From 2015 we developed hard toward Ruby 3, whose goal is performance, concurrency, and Typing. Especially about performance, Matz stated "Ruby3 will be 3 times faster than Ruby2" a.k.a. [Ruby 3x3](https://blog.heroku.com/ruby-3-by-3). + +![Optcarrot 3000 graph](https://i.imgur.com/mqOkcWi.png) + +With [Optcarrot benchmark](https://github.com/mame/optcarrot), which measures single thread performance based on NES's game emulation workload, it achieved 3x faster performance than Ruby 2.0!
These were measured at the environment written in https://benchmark-driver.github.io/hardware.html. [8c510e4095](http://github.com/ruby/ruby/commit/8c510e4095) was used as Ruby 3.0. It may not be 3x faster depending on your environment or benchmark.
+ +Ruby 3.0.0 covers those goals by +* Performance + * MJIT +* Concurrency + * Ractor + * Fiber Scheduler +* Typing (Static Analysis) + * RBS + * TypeProf + +With above performance improvement Ruby 3.0 introduces a number of new features described below. + +## Performance + +> When I first declared "Ruby3x3" in the conference keynote, many including members of the core team felt "Matz is a boaster". In fact, I felt so too. But we did. I am honored to see the core team actually accomplished to make Ruby3.0 three times faster than Ruby2.0 (in some benchmarks). -- Matz + +### MJIT + +Many improvements were implemented in MJIT. See NEWS for details. + +As of Ruby 3.0, JIT is supposed to give performance improvements in limited workloads, such as games ([Optcarrot](https://benchmark-driver.github.io/benchmarks/optcarrot/commits.html#chart-1)), AI ([Rubykon](https://benchmark-driver.github.io/benchmarks/rubykon/commits.html)), or whatever application that spends majority of time in calling a few methods many times. + +Although Ruby 3.0 [significantly decreased a size of JIT-ed code](https://twitter.com/k0kubun/status/1256142302608650244), it is still not ready for optimizing workloads like Rails, which often spend time on so many methods and therefore suffer from i-cache misses exacerbated by JIT. Stay tuned for Ruby 3.1 for further improvements on this issue. + +## Concurrency / Parallel + +> It's multi-core age today. Concurrency is very important. With Ractor, along with Async Fiber, Ruby will be a real concurrent language. --- Matz + +### Ractor (experimental) +Ractor is an Actor-model like concurrent abstraction designed to provide a parallel execution feature without thread-safety concerns. + +You can make multiple ractors and you can run them in parallel. Ractor enables you to make thread-safe parallel programs because ractors can not share normal objects. Communication between ractors are supported by exchaning messages. + +To limit sharing of objects, Ractor introduces several restrictions to the Ruby's syntax (without multiple Ractors, there is no restriction). + +The specification and implementation are not matured and may be changed in the future, so this feature is marked as experimental and show the "experimental feature" warning when the first `Ractor.new`. + +The following small program measures the execution time of famous benchmark tak function ([Tak (function) - Wikipedia](https://en.wikipedia.org/wiki/Tak_(function))), by executing it 4 times sequentially or 4 times in parallel with ractors. + +``` ruby +def tarai(x, y, z) = + x <= y ? y : tarai(tarai(x-1, y, z), + tarai(y-1, z, x), + tarai(z-1, x, y)) +require 'benchmark' +Benchmark.bm do |x| + # sequential version + x.report('seq'){ 4.times{ tarai(14, 7, 0) } } + + # parallel version + x.report('par'){ + 4.times.map do + Ractor.new { tarai(14, 7, 0) } + end.each(&:take) + } +end +``` + +``` +Benchmark result: + user system total real +seq 64.560736 0.001101 64.561837 ( 64.562194) +par 66.422010 0.015999 66.438009 ( 16.685797) +``` + +The result was measured on Ubuntu 20.04, Intel(R) Core(TM) i7-6700 (4 cores, 8 hardware threads). It shows that the parallel version is 3.87 times faster than the sequential version. + + +See [doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md) for more details. + +### Fiber Scheduler + +`Fiber#scheduler` is introduced for intercepting blocking operations. This allows for light-weight concurrency without changing existing code. Watch ["Don't Wait For Me, Scalable Concurrency for Ruby 3"](https://www.youtube.com/watch?v=Y29SSOS4UOc) for an overview of how it works. + +Currently supported classes/methods: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` and related methods (e.g. `#wait_readable`, `#gets`, `#puts` and so on). +- `IO#select` is *not supported*. + +This example program will perform several HTTP requests concurrently: + +``` ruby +require 'async' +require 'net/http' +require 'uri' + +Async do + ["ruby", "rails", "async"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + +It uses [async](https://github.com/socketry/async) which provides the event loop. This event loop uses the `Fiber#scheduler` hooks to make `Net::HTTP` non-blocking. Other gems can use this interface to provide non-blocking execution for Ruby, and those gems can be compatible with other implementations of Ruby (e.g. JRuby, TruffleRuby) which can support the same non-blocking hooks. + +## Static Analysis + +> 2010s were an age of statically type programming languages. Ruby seeks the future with static type checking, without type declaration, using abstract interpretation. RBS & TypeProf are the first step to the future. More steps to come. --- Matz + +### RBS + +RBS is a language to describe the types of Ruby programs. + +Type checkers including TypeProf and other tools supporting RBS will understand Ruby programs much better with RBS definitions. + +You can write down the definition of classes and modules: methods defined in the class, instance variables and their types, and inheritance/mix-in relations. + +The goal of RBS is to support commonly seen patterns in Ruby programs and it allows writing advanced types including union types, method overloading, and generics. It also supports duck typing with _interface types_. + +Ruby 3.0 ships with `rbs` gem, which allows parsing and processing type definitions written in RBS. +The following is a small example of RBS with class, module, and constant definitions. + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|` means union types, `User` or `Bot`. + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # Method overloading is supported. + | (File, from: User | Bot) -> Message + end +end +``` + +See [README of rbs gem](https://github.com/ruby/rbs) for more detail. + +### TypeProf + +TypeProf is a type analysis tool bundled in the Ruby package. + +Currently, TypeProf serves as a kind of type inference. + +It reads plain (non-type-annotated) Ruby code, analyzes what methods are defined and how they are used, and generates a prototype of type signature in RBS format. + +Here is a simple demo of TypeProf. + +An example input: + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +An example output: + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +You can run TypeProf by saving the input as "test.rb" and invoke a command called "typeprof test.rb". + +You can also [try TypeProf online](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=). (It runs TypeProf on the server side, so sorry if it is out!) + +See [the documentation](https://github.com/ruby/typeprof/blob/master/doc/doc.md) and [demos](https://github.com/ruby/typeprof/blob/master/doc/demo.md) for details. + +TypeProf is experimental and not so mature yet; only a subset of the Ruby language is supported, and the detection of type errors is limited. But it is still growing rapidly to improve the coverage of language features, the analysis performance, and usability. Any feedback is very welcome. + +## Other Notable New Features + +* One-line pattern matching is redesigned. (experimental) + + * `=>` is added. It can be used as like rightward assignment. + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` + * `in` is changed to return `true` or `false`. + + ```ruby + # version 3.0 + 0 in 1 #=> false + + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` + +* Find pattern is added. (experimental) + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* Endless method definition is added. + + ``` ruby + def square(x) = x * x + ``` + +* `Hash#except` is now built-in. + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + +* Memory view is added as an experimental feature + + * This is a new C-API set to exchange a raw memory area, such as a numeric array and a bitmap image, between extension libraries. The extension libraries can share also the metadata of the memory area that consists of the shape, the element format, and so on. Using these kinds of metadata, the extension libraries can share even a multidimensional array appropriately. This feature is designed by referring to Python's buffer protocol. + +## Performance improvements + +* Pasting long code to IRB is 53 times faster than bundled with Ruby 2.7.0. For example, the time required to paste [this sample code](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) goes from 11.7 seconds to 0.22 seconds. + + + + + +* The `measure` command has been added to IRB. It allows simple execution time measurement. + + ``` + irb(main):001:0> 3 + => 3 + irb(main):002:0> measure + TIME is added. + => nil + irb(main):003:0> 3 + processing time: 0.000058s + => 3 + irb(main):004:0> measure :off + => nil + irb(main):005:0> 3 + => 3 + ``` + +## Other notable changes since 2.7 + +* Keyword arguments are separated from other arguments. + * In principle, code that prints a warning on Ruby 2.7 won't work. See the [document](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/) in detail. + * By the way, arguments forwarding now supports leading arguments. + + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` + +* Pattern matching (`case/in`) is no longer experimental. +* The `$SAFE` feature was completely removed; now it is a normal global variable. +* The order of backtrace had been reversed at Ruby 2.5, and is reverted. Now it behaves like Ruby 2.4; an error message and the line number where the exception occurs are printed first, and its callers are printed later. +* Some standard libraries are updated. + * RubyGems 3.2.3 + * Bundler 2.2.3 + * IRB 1.2.6 + * Reline 0.1.5 + * Pysch 3.3.0 + * JSON 2.5.0 + * BigDecimal 3.0.0 + * CSV 3.1.9 + * Date 3.1.1 + * Digest 3.0.0 + * Fiddle 1.0.5 + * StringIO 3.0.0 + * StringScanner 3.0.0 + * etc. +* The following libraries are no longer bundled gems or standard libraries. + Install the corresponding gems to use these features. + * sdbm + * webrick + * net-telnet + * xmlrpc +* The following default gems are now bundled gems. + * rexml + * rss +* The following stdlib files are now default gems and are published on rubygems.org. + * English + * abbrev + * base64 + * drb + * debug + * erb + * find + * net-ftp + * net-http + * net-imap + * net-protocol + * open-uri + * optparse + * pp + * prettyprint + * resolv-replace + * resolv + * rinda + * set + * securerandom + * shellwords + * tempfile + * tmpdir + * time + * tsort + * un + * weakref + * digest + * io-nonblock + * io-wait + * nkf + * pathname + * syslog + * win32ole + +See [NEWS](https://github.com/ruby/ruby/blob/{{ release.tag }}/NEWS.md) +or [commit logs](https://github.com/ruby/ruby/compare/v2_7_0...{{ release.tag }}) +for more details. + +With those changes, [{{ release.stats.files_changed }} files changed, {{ release.stats.insertions }} insertions(+), {{ release.stats.deletions }} deletions(-)](https://github.com/ruby/ruby/compare/v2_7_0...{{ release.tag }}#file_bucket) +since Ruby 2.7.0! + +> Ruby3.0 is a milestone. The language is evolved, keeping compatibility. But it's not the end. Ruby will keep progressing, and become even greater. Stay tuned! --- Matz + +Please try Ruby {{ release.version }}, and give us any feedback! + +## Download + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## What is Ruby + +Ruby was first developed by Matz (Yukihiro Matsumoto) in 1993, +and is now developed as Open Source. It runs on multiple platforms +and is used all over the world especially for web development. diff --git a/ja/news/_posts/2020-12-25-ruby-3-0-0-released.md b/ja/news/_posts/2020-12-25-ruby-3-0-0-released.md new file mode 100644 index 0000000000..ba20cb3d7e --- /dev/null +++ b/ja/news/_posts/2020-12-25-ruby-3-0-0-released.md @@ -0,0 +1,383 @@ +--- +layout: news_post +title: "Ruby 3.0.0 リリース" +author: "naruse" +translator: +date: 2020-12-25 00:00:00 +0000 +lang: ja +--- +{% assign release = site.data.releases | where: "version", "3.0.0" | first %} + +Ruby 3.0系初のリリースである、Ruby {{ release.version }} が公開されました。 + +これまで、Ruby3に向けてパフォーマンスの改善、並行処理、静的解析という3つの目標を掲げて、活発に開発が行われてきました。特にパフォーマンスの改善については、[Ruby 3x3](https://blog.heroku.com/ruby-3-by-3) として「Ruby3はRuby2の3倍速くする」ことを目指してきました。 + +![Optcarrot 3000 graph](https://i.imgur.com/mqOkcWi.png) + +Ruby 3.0では開発の指標の一つとしてきた[Optcarotベンチマーク](https://github.com/mame/optcarrot)で3倍を達成するとともに、以下のような取り組みが行われています。
These were measured at the environment written in https://benchmark-driver.github.io/hardware.html. [8c510e4095](http://github.com/ruby/ruby/commit/8c510e4095) was used as Ruby 3.0. It may not be 3x faster depending on your environment or benchmark.
+ + +Ruby 3 では以下の目標を達成しました。 +* パフォーマンスの改善 + * MJIT +* 並行処理 + * Ractor + * Fiber Scheduler +* 静的解析 + * RBS + * TypeProf + +他にも、Ruby 3.0 では Ruby 2.7 に比べて、多くの新しい機能やパフォーマンスの改善が含まれます。 その一部を以下に紹介します。 + +## パフォーマンスの改善 + +> わたしが最初にRuby3x3というスローガンを宣言した時、コアチームメンバーを含むほとんどの人は、「またそんな夢物語を」と思ったことでしょう。実際、わたしもそう思ってました。しかし、皆の努力によって(ある程度)達成できました。この成果をこころから誇りに思います。 --- Matz + +### MJIT + +Many improvements were implemented in MJIT. See NEWS for details. + +As of Ruby 3.0, JIT is supposed to give performance improvements in limited workloads, such as games ([Optcarrot](https://benchmark-driver.github.io/benchmarks/optcarrot/commits.html#chart-1)), AI ([Rubykon](https://benchmark-driver.github.io/benchmarks/rubykon/commits.html)), or whatever application that spends majority of time in calling a few methods many times. + +Although Ruby 3.0 [significantly decreased a size of JIT-ed code](https://twitter.com/k0kubun/status/1256142302608650244), it is still not ready for optimizing workloads like Rails, which often spend time on so many methods and therefore suffer from i-cache misses exacerbated by JIT. Stay tuned for Ruby 3.1 for further improvements on this issue. + +## Concurrency / Parallel + +> マルチコア時代と呼んでも過言ではない現代、コンカレンシーは非常に重要です。RactorとAsync Fiberの導入でようやくRubyもコンカレント言語になれそうです。 -- Matz + +### Ractor (experimental) + +Ractor はアクターモデル風の並行・並列制御機構であり、スレッド安全に関する懸念なく、Rubyで並列処理を行うための機能として設計されています。 + +複数のRactorを作成すると、それらは並列計算機上で並列に実行されます。Ractor間では、ほとんどのオブジェクトが共有できないように設計されているため、スレッド安全なプログラムにすることができます。メッセージの送受信により、Ractor間のコミュニケーションを行うことが可能です。 + +Ractor間でのオブジェクトの共有を制限するために、複数Ractorでの実行時には、いくつかのRubyの機能に制限が入ります(ただし、複数のRactorを用いない場合には、これまでのRubyと何も変わりません)。 + +Ractorの仕様と実装は、まだ発展途上であるため、実験的機能として提供されます。初回のRactorの生成時には実験的機能であることが警告で表示されます。 + +次の小さなプログラムでは、有名なベンチマーク用関数である竹内関数([竹内関数 - Wikipedia](https://ja.wikipedia.org/wiki/%E7%AB%B9%E5%86%85%E9%96%A2%E6%95%B0) )を用いて、4回逐次的に実行する場合と、Ractorを用いて4並列で実行する場合で、それぞれ実行時間を計測しています。 + +``` ruby +def tarai(x, y, z) = + x <= y ? y : tarai(tarai(x-1, y, z), + tarai(y-1, z, x), + tarai(z-1, x, y)) +require 'benchmark' +Benchmark.bm do |x| + # sequential version + x.report('seq'){ 4.times{ tarai(14, 7, 0) } } + + # parallel version + x.report('par'){ + 4.times.map do + Ractor.new { tarai(14, 7, 0) } + end.each(&:take) + } +end +``` + +``` +Benchmark result: + user system total real +seq 64.560736 0.001101 64.561837 ( 64.562194) +par 66.422010 0.015999 66.438009 ( 16.685797) +``` + +結果は Ubuntu 20.04, Intel(R) Core(TM) i7-6700 (4 cores, 8 hardware threads) で実行したものになります。逐次実行したときよりも、並列化によって3.87倍の高速化していることがわかります。 + + +より詳細は、[doc/ractor.md](https://github.com/ruby/ruby/blob/master/doc/ractor.md) をご覧ください。 + +### Fiber Scheduler + +`Fiber#scheduler` is introduced for intercepting blocking operations. This allows for light-weight concurrency without changing existing code. Watch ["Don't Wait For Me, Scalable Concurrency for Ruby 3"](https://www.youtube.com/watch?v=Y29SSOS4UOc) for an overview of how it works. + +Currently supported classes/methods: + +- `Mutex#lock`, `Mutex#unlock`, `Mutex#sleep` +- `ConditionVariable#wait` +- `Queue#pop`, `SizedQueue#push` +- `Thread#join` +- `Kernel#sleep` +- `Process.wait` +- `IO#wait`, `IO#read`, `IO#write` and related methods (e.g. `#wait_readable`, `#gets`, `#puts` and so on). +- `IO#select` is *not supported*. + +This example program will perform several HTTP requests concurrently: + +``` ruby +require 'async' +require 'net/http' +require 'uri' + +Async do + ["ruby", "rails", "async"].each do |topic| + Async do + Net::HTTP.get(URI "https://www.google.com/search?q=#{topic}") + end + end +end +``` + +It uses [async](https://github.com/socketry/async) which provides the event loop. This event loop uses the `Fiber#scheduler` hooks to make `Net::HTTP` non-blocking. Other gems can use this interface to provide non-blocking execution for Ruby, and those gems can be compatible with other implementations of Ruby (e.g. JRuby, TruffleRuby) which can support the same non-blocking hooks. + +## 静的解析 + +> 2010年代は静的型言語の時代でした。Rubyは抽象解釈を武器に、型宣言なしで静的型チェックする未来を目指します。RBSとTypeProfはその第一歩です。Rubyがもたらす誰も見たことがない静的型の世界を見守ってください --- Matz + +### RBS + +RBSはRubyプログラムの型を記述するための言語です。 + +TypeProfなどの型検査ツールを初めとする静的解析を行うツールは、RBSを利用することでRubyプログラムをより精度良く解析することができます。 + +RBSでは、Rubyプログラムのクラスやモジュールの型を定義します。メソッドやインスタンス変数、定数とその型、継承やmixinなどの関係などが記述できます。 + +RBSはRubyプログラムに頻出するパターンをサポートするように設計されており、ユニオン型、メソッドオーバーロード、ジェネリクスなどの機能を提供します。さらに「インタフェース型」によってダックタイピングをサポートします。 + +Ruby 3.0には、このRBS言語で書かれた型定義を処理するためのライブラリである `rbs` gemが同梱されています。 + +クラスやモジュール、定数を定義する、簡単なRBSの例を示します。 + +``` rbs +module ChatApp + VERSION: String + class Channel + attr_reader name: String + attr_reader messages: Array[Message] + attr_reader users: Array[User | Bot] # `|` は `User` か `Bot` のインスタンスを表現する「ユニオン型」です + def initialize: (String) -> void + def post: (String, from: User | Bot) -> Message # メソッドオーバーロードを記述することもできます + | (File, from: User | Bot) -> Message + end +end +``` + +詳細については、[rbs gemのREADME](https://github.com/ruby/rbs)を参照してください。 + +### TypeProf + +TypeProf は Ruby パッケージに同梱された型解析ツールです。 + +TypeProf の現在の主な用途は一種の型推論です。 + +型注釈の無い普通の Ruby コードを入力し、どんなメソッドが定義されどのように使われているかを解析し、型シグネチャのプロトタイプを RBS フォーマットで生成します。 + +次は TypeProf の簡単なデモです。 + +サンプル入力 + +``` ruby +# test.rb +class User + def initialize(name:, age:) + @name, @age = name, age + end + attr_reader :name, :age +end +User.new(name: "John", age: 20) +``` + +サンプル出力 + +``` +$ typeprof test.rb +# Classes +class User + attr_reader name : String + attr_reader age : Integer + def initialize : (name: String, age: Integer) -> [String, Integer] +end +``` + +サンプル入力を"test.rb"という名前で保存し、`typeprof test.rb`というコマンドで TypeProf の解析ができます。 + +[TypeProf をオンラインで試す](https://mame.github.io/typeprof-playground/#rb=%23+test.rb%0Aclass+User%0A++def+initialize%28name%3A%2C+age%3A%29%0A++++%40name%2C+%40age+%3D+name%2C+age%0A++end%0A++%0A++attr_reader+%3Aname%2C+%3Aage%0Aend%0A%0AUser.new%28name%3A+%22John%22%2C+age%3A+20%29&rbs=)こともできます(サーバサイドで TypeProf を動かしているので、サーバが落ちたらごめんなさい)。 + +詳しくは[ドキュメント](https://github.com/ruby/typeprof/blob/master/doc/doc.md)や[デモ](https://github.com/ruby/typeprof/blob/master/doc/demo.md)を見てください。 + +残念ながら TypeProf はまだ実験的で、あまり完成度は高くありません。Ruby 言語のサブセットだけがサポートされていて、型エラー検出の機能は限定的です。ですがいま急速に改良中であり、言語機能のカバレッジ増強、解析効率の向上、利便性の向上などを行っています。フィードバックを歓迎します。 + +## その他の主要な新機能 + +* 1行パターンマッチが再設計されました。 (experimental) + + * `=>` を新たに使うようになりました。右代入のように使うことができます。 + + ```ruby + 0 => a + p a #=> 0 + + {b: 0, c: 1} => {b:} + p b #=> 0 + ``` + + * `in` は `true` または `false` を返すようになりました。 + + ```ruby + # version 3.0 + 0 in 1 #=> false + + # version 2.7 + 0 in 1 #=> raise NoMatchingPatternError + ``` + +* findパターンが追加されました。 (experimental) + + ``` ruby + case ["a", 1, "b", "c", 2, "d", "e", "f", 3] + in [*pre, String => x, String => y, *post] + p pre #=> ["a", 1] + p x #=> "b" + p y #=> "c" + p post #=> [2, "d", "e", "f", 3] + end + ``` + +* 一行メソッド定義が書けるようになりました。 + + ``` ruby + def square(x) = x * x + ``` + +* `Hash#except` が組み込みになりました。 + + ``` ruby + h = { a: 1, b: 2, c: 3 } + p h.except(:a) #=> {:b=>2, :c=>3} + ``` + +## パフォーマンスの改善 + +* IRB への長いコードの貼り付けは、Ruby 2.7.0 にバンドルされているものと比較して 53 倍の速さになります。例えば、[このサンプルコード](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b)の貼り付けに要する時間は、11.7 秒から 0.22 秒になります。 + + + + +* IRB に `measure` コマンドが追加されました。簡単な実行時間計測が可能です。 + + ``` + irb(main):001:0> 3 + => 3 + irb(main):002:0> measure + TIME is added. + => nil + irb(main):003:0> 3 + processing time: 0.000058s + => 3 + irb(main):004:0> measure :off + => nil + irb(main):005:0> 3 + => 3 + ``` + +## その他の注目すべき 2.7 からの変更点 + +* キーワード引数が通常の引数から分離されました。 + * 原則として、2.7 で警告の出ていたコードは動かなくなります。詳細は[別ドキュメント](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/)を参照してください。 + * 関連して、引数のフォワーディングの記法で先頭に引数を書けるようになりました。 + + ``` ruby + def method_missing(meth, ...) + send(:"do_#{ meth }", ...) + end + ``` + +* パターンマッチ(`case/in`)が実験的な機能ではなくなりました。 +* `$SAFE` の機能が完全に削除され、ただのグローバル変数となりました。 +* バックトレースの順序は2.5で逆転しましたが、3.0ではこれを取りやめることになりました。例外が起きた行が先に表示され、呼び出し元が後に表示されるように戻ります。 +* いくつかの標準ライブラリがアップデートされました。 + * RubyGems 3.2.3 + * Bundler 2.2.3 + * IRB 1.2.6 + * Reline 0.1.5 + * Pysch 3.3.0 + * JSON 2.5.0 + * BigDecimal 3.0.0 + * CSV 3.1.9 + * Date 3.1.1 + * Digest 3.0.0 + * Fiddle 1.0.5 + * StringIO 3.0.0 + * StringScanner 3.0.0 + * etc. +* 以下のライブラリは標準添付ライブラリから削除されました。3.0 以降で使いたい場合は rubygems から利用してください。 + * sdbm + * webrick + * net-telnet + * xmlrpc +* 以下のライブラリが新たに bundled gems になりました。Bundler から利用する場合は Gemfile に明示的に指定してください。 + * rexml + * rss +* 以下のライブラリが新たに default gems になりました。rubygems.org からアップデート可能です。 + * English + * abbrev + * base64 + * drb + * debug + * erb + * find + * net-ftp + * net-http + * net-imap + * net-protocol + * open-uri + * optparse + * pp + * prettyprint + * resolv-replace + * resolv + * rinda + * set + * securerandom + * shellwords + * tempfile + * tmpdir + * time + * tsort + * un + * weakref + * digest + * io-nonblock + * io-wait + * nkf + * pathname + * syslog + * win32ole + +その他詳細については、[NEWS](https://github.com/ruby/ruby/blob/{{ release.tag }}/NEWS.md) ファイルまたは[コミットログ](https://github.com/ruby/ruby/compare/v2_7_0...{{ release.tag }})を参照してください。 + +なお、こうした変更により、Ruby 2.7.0 以降では [{{ release.stats.files_changed }} 個のファイルに変更が加えられ、{{ release.stats.insertions }} 行の追加と {{ release.stats.deletions }} 行の削除が行われました](https://github.com/ruby/ruby/compare/v2_7_0...{{ release.tag }}#file_bucket) ! + +> Ruby3.0はマイルストーンです。言語は互換性を保ったまま大きく進化しました。しかし、これで終わりではありません。今後もRubyは進化し続け、より偉大な言語になることでしょう。ご期待下さい!。 --- Matz + +メリークリスマス、様々な機能が追加された Ruby 3.0 をぜひお楽しみ下さい! + +## ダウンロード + +* <{{ release.url.gz }}> + + SIZE: {{ release.size.gz }} + SHA1: {{ release.sha1.gz }} + SHA256: {{ release.sha256.gz }} + SHA512: {{ release.sha512.gz }} + +* <{{ release.url.xz }}> + + SIZE: {{ release.size.xz }} + SHA1: {{ release.sha1.xz }} + SHA256: {{ release.sha256.xz }} + SHA512: {{ release.sha512.xz }} + +* <{{ release.url.zip }}> + + SIZE: {{ release.size.zip }} + SHA1: {{ release.sha1.zip }} + SHA256: {{ release.sha256.zip }} + SHA512: {{ release.sha512.zip }} + +## Ruby とは + +Rubyはまつもとゆきひろ (Matz) によって1993年に開発が始められ、今もオープンソースソフトウェアとして開発が続けられています。Rubyは様々なプラットフォームで動き、世界中で、特にWebアプリケーション開発のために使われています。 From 02756c5626ebddd58172eb47afa9e79a240a7fd5 Mon Sep 17 00:00:00 2001 From: "NARUSE, Yui" Date: Fri, 25 Dec 2020 13:59:50 +0900 Subject: [PATCH 0022/1292] Edit image and video (#2577) * Edit image and video * translate MJIT * Use ruby's s3 --- en/news/_posts/2020-12-25-ruby-3-0-0-released.md | 6 +++--- ja/news/_posts/2020-12-25-ruby-3-0-0-released.md | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/en/news/_posts/2020-12-25-ruby-3-0-0-released.md b/en/news/_posts/2020-12-25-ruby-3-0-0-released.md index 2cf09596b4..e9826920df 100644 --- a/en/news/_posts/2020-12-25-ruby-3-0-0-released.md +++ b/en/news/_posts/2020-12-25-ruby-3-0-0-released.md @@ -10,7 +10,7 @@ lang: en We are pleased to announce the release of Ruby {{ release.version }}. From 2015 we developed hard toward Ruby 3, whose goal is performance, concurrency, and Typing. Especially about performance, Matz stated "Ruby3 will be 3 times faster than Ruby2" a.k.a. [Ruby 3x3](https://blog.heroku.com/ruby-3-by-3). -![Optcarrot 3000 graph](https://i.imgur.com/mqOkcWi.png) +Optcarrot 3000 frames With [Optcarrot benchmark](https://github.com/mame/optcarrot), which measures single thread performance based on NES's game emulation workload, it achieved 3x faster performance than Ruby 2.0!
These were measured at the environment written in https://benchmark-driver.github.io/hardware.html. [8c510e4095](http://github.com/ruby/ruby/commit/8c510e4095) was used as Ruby 3.0. It may not be 3x faster depending on your environment or benchmark.
@@ -250,7 +250,7 @@ TypeProf is experimental and not so mature yet; only a subset of the Ruby langua * Pasting long code to IRB is 53 times faster than bundled with Ruby 2.7.0. For example, the time required to paste [this sample code](https://gist.github.com/aycabta/30ab96334275bced5796f118c9220b0b) goes from 11.7 seconds to 0.22 seconds. -