Rubyで配列を操作するときの7つのトリック

ルビー配列

この記事では、Rubyで配列を効果的に使用および操作する方法に関するいくつかの興味深いトリックについて説明します。 もちろん、使用可能なすべてのメソッドを詳細に説明するRubiDocおよび他の多くのリソースがありますが、ここでは使用方法を正確に共有したいと思います。


1.別の配列のすべての要素を含む配列を確認する方法


たとえば、チェックする場合、またはインポートされたすべての電子メールが既に連絡先リストにある場合:
imported_emails = [ 'john@doe.com', 'janet@doe.com' ] existing_emails = [ 'john@doe.com', 'janet@doe.com' , 'fred@mercury.com' ] puts 'already imported' if (imported_emails - existing_emails).empty? 

IRBで起動
すでにインポートされています
=> nil

2. 2つの配列で共通の要素を見つける方法


たとえば、2つの異なる投稿で共通のタグを見つける必要がある場合:
 tags_post1 = [ 'ruby', 'rails', 'test' ] tags_post2 = [ 'test', 'rspec' ] common_tags = tags_post1 & tags_post2 

IRBで起動
=> [「テスト」]

3.重複する要素を複製せずに2つの配列を接続する方法


 followeds1 = [ 1, 2, 3 ] followeds2 = [ 2, 4, 5 ] all_followeds = followeds1 | followeds2 

IRBで起動
=> [1、2、3、4、5]

4.ハッシュ配列をソートする方法


たとえば、ハッシュの配列の形式で、ある種のAPIからデータを取得します。
 data = [ { name: 'Christophe', location: 'Belgium' }, { name: 'John', location: 'United States of America' }, { name: 'Piet', location: 'Belgium' }, { name: 'François', location: 'France' } ] 

表示されたら、場所フィールドで並べ替えてから、次の操作を行います。
 data.sort_by { |hsh| hsh[:location] } 

IRBで起動
=> [
{:名前=> "クリストフ"、:場所=> "ベルギー"}、
{:name => "Piet" ,: location => "Belgium"}、
{:名前=>“François” ,:場所=>“フランス”}、
{:name => "John" ,: location => "United States of America"}
]

5.特定の属性によって配列の一意の要素を取得する方法


たとえば、メインページにランダムな商品を表示したいが、各商品が1つのカテゴリからのみ取得されるようにする場合:
 Product = Struct.new(:id, :category_id) products = [ Product.new(1, 1), Product.new(2, 2), Product.new(3, 3), Product.new(4, 1), Product.new(5, 3), Product.new(6, 5), ] products = products.uniq &:category_id 

IRBで起動
=> [
#<struct Product id = 1、category_id = 1>、
#<struct Product id = 2、category_id = 2>、
#<struct Product id = 3、category_id = 3>、
#<struct Product id = 6、category_id = 5>
]


6.配列の文字列要素をフィルタリングする方法


たとえば、あるキーワードでフィルタリングしたい本の名前を含む配列がある場合があります。
 books = [ 'The Ruby Programming Language', 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers\' Guide (The Facets of Ruby)', 'Practical Object-Oriented Design in Ruby: An Agile Primer', 'Eloquent Ruby', 'Ruby on Rails Tutorial: Learn Web Development with Rails' ] books = books.grep(/[Rr]ails/) 

IRBで起動
=> [「Ruby on Railsチュートリアル:Railsを使用したWeb開発を学ぶ」]

7.常に配列を返す方法


たとえば、製品のリストまたは単一の製品を返すことができるメソッドがあります。 戻り値が常に配列であることを確認するには、Array()または[*]を使用できます。
 def method # … [*products] end 

Source: https://habr.com/ru/post/J213813/


All Articles