簡體   English   中英

從對象數組中提取紅寶石哈希元素值

[英]Extract ruby hash element value from an array of objects

我有以下數組

[#<Attachment id: 73, container_id: 1, container_type: "Project", filename: "Eumna.zip", disk_filename: "140307233750_Eumna.zip", filesize: 235303, content_type: nil, digest: "9a10843635b9e9ad4241c96b90f4d331", downloads: 0, author_id: 1, created_on: "2014-03-07 17:37:50", description: "", disk_directory: "2014/03">, #<Attachment id: 74, container_id: 1, container_type: "Project", filename: "MainApp.cs", disk_filename: "140307233750_MainApp.cs", filesize: 1160, content_type: nil, digest: "6b985033e19c5a88bb5ac4e87ba4c4c2", downloads: 0, author_id: 1, created_on: "2014-03-07 17:37:50", description: "", disk_directory: "2014/03">]

我需要從該字符串(附件ID)中提取值73和74。

有什么辦法可以提取這個值

以防萬一作者表示他有一個實際的String實例:

string = '[#<Attachment id: 73, container_id: 1, container_type: "Project", filename: "Eumna.zip", disk_filename: "140307233750_Eumna.zip", filesize: 235303, content_type: nil, digest: "9a10843635b9e9ad4241c96b90f4d331", downloads: 0, author_id: 1, created_on: "2014-03-07 17:37:50", description: "", disk_directory: "2014/03">, #<Attachment id: 74, container_id: 1, container_type: "Project", filename: "MainApp.cs", disk_filename: "140307233750_MainApp.cs", filesize: 1160, content_type: nil, digest: "6b985033e19c5a88bb5ac4e87ba4c4c2", downloads: 0, author_id: 1, created_on: "2014-03-07 17:37:50", description: "", disk_directory: "2014/03">]'

string.scan(/\\sid: (\\d+)/).flatten => [“ 73”,“ 74”]

使用Array#collect執行以下操作:

array.collect(&:id)

如果是字符串,請使用JSON::parse首先從字符串中獲取數組,然后使用Array#collect方法,如下所示:

require 'json'
array = JSON.parse(string)
array.collect(&:id)

數組的元素(我將其a )看起來像類Attachment實例(不是字符串)。 您可以通過在IRB中執行e.class來確認這一點,其中e是任何元素a (例如a.first )。 我的假設是正確的,如果它返回Attachment 以下假設是這種情況。

@Arup顯示了如何在實例變量@id具有訪問器(用於讀取)時檢索其值:

a.map(&:id)

(又稱collect )。 您可以執行以下命令來查看@id是否具有訪問器

e.instance_methods(false)

對於任何元件ea 這將返回一個數組,其中包含為Attachment類定義的所有實例方法。 (參數false導致Ruby的內置方法被排除。)如果@id沒有訪問器,則需要使用Object @ instance_variable_get

a.map { |e| e.instance_variable_get(:@id) }

(您也可以將參數寫為字符串: "@id" )。

如果

s = '[#<Attachment id: 73, container_id: 1,..]'

實際上是一個字符串,但是您忽略了將其用(單引號)引起來,則必須執行

a = eval(s)

將其轉換為Attachment實例的數組,然后才能提取:@a的值。

聽到“點擊”? 那是我開始我的秒表。 我想看看發表評論要花多長時間,這讓我為使用(惡意的) eval提出建議而感到eval

有兩個建議:將代碼簡化為基本內容,並避免讀者水平滾動以閱讀代碼。 例如,在這里,您可能這樣寫:

a = [#<Attachment id: 73, container_id: 1>, #<Attachment id: 74, container_id: 1>]

我刪除的所有實例變量都與問題無關。

如果太長而無法容納一行(不進行水平滾動,則寫為:

a = [#<Attachment id: 73, container_id: 1>,
     #<Attachment id: 74, container_id: 1>]

最后,作為SO的新手,請看一下本指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM