21
array.include? 'foo' or array.include? 'bar'

は構文エラーです (予期しない keyword_or)。括弧は問題を解決しますが、私は Ruby に慣れていないので、次のうちどれがより慣用的であると考えられるかわかりません。

オプション1

array.include?('foo') or array.include?('bar')

オプション 2

(array.include? 'foo') or (array.include? 'bar')

これは個人的な好みに帰着しますか、それとも 1 つのアプローチがより「正しい」と見なされますか?

4

4 に答える 4

27

コミュニティ主導の Ruby コーディング スタイル ガイド、特にSyntaxのセクションをご覧になることをお勧めします。

内部 DSL の一部であるメソッド (Rake、Rails、RSpec など)、Ruby で「キーワード」ステータスのメソッド (attr_reader、puts など)、および属性アクセス メソッドのパラメーターを囲む括弧を省略します。他のすべてのメソッド呼び出しの引数を括弧で囲みます。- ガイドからの抜粋

class Person
  attr_reader :name, :age

  # omitted
end

temperance = Person.new('Temperance', 30)
temperance.name

puts temperance.age

x = Math.sin(y)
array.delete(e)
于 2011-10-10T05:25:43.990 に答える
4

それが失敗していると確信していますか?あなたの最初の例は私にとってはうまくいきます。

ruby-1.9.2-p290 :002 > array = ['bar']
 => ["bar"] 
ruby-1.9.2-p290 :003 > array.include? 'foo' or array.include? 'bar'
 => true

As a matter of fact, if anything could be considered idiomatic it would be that one. The low precedence of or allows this to work when you leave the parens off. This characteristic is something that should make it idiomatic to Ruby (and even Perl, which or is a hold over from).

Option 1 is super clear, but considering you included the parens you really have no need to use or. It's probably better to use ||, which has a high precedence like other operators and is just more common. I think using or for the sake of it looking like english is not a great practice. It has a semantic meaning within the language and is probably best used for those qualities.

Option 2 is silly of course. If you're going to include parens, you might as well use them for the method signature.

Hope this helps.

于 2011-10-10T02:05:48.380 に答える
4

Avdi Grimm は、 orをブール論理に使用すべきではないと考えています。制御フローに対してのみまたはを使用する必要があります (またはに類似) 。andorandorifunless

彼の推奨によると、||代わりに次を使用する必要があります。

array.include?('foo') || array.include?('bar')
于 2011-10-10T02:07:10.583 に答える
2

オプション 1 は、他の言語にも共通であるため、推奨されます。オプション 2 は、最近ではあまり使われていない LISP のように見えます。

于 2011-10-10T01:47:21.363 に答える