2014-02-14 49 views
0

對於奇怪的措辭,我很抱歉。我不知道你在說什麼。我有這個數組:通過其內容獲取數組的元素

[#<Item:0x007faeea066508 @name="Backpack", @exam="Not much here... just a backpack">] 

這是一個庫存數組。用戶將輸入類似「檢查揹包」的東西,它將返回元素的@exam。如果只知道@name,你會如何獲得該元素?謝謝!

+0

如果讀者對這個數組感到困惑,它會包含一個元素:類Item的一個實例。 –

回答

1

這是你擁有的一切:

class Item 
    # accessors for @name and @exam possibly defined here 
    def initialize(name, exam) 
    @name = name 
    @exam = exam 
    end 
    # methods possibly defined here 
end 

item = Item.new("Backpack", "Just a backpack") 
    #=> #<Item:0x0000010201dda0 @name="Backpack", @exam="Just a backpack"> 

所以,你有一個數組a一個元素,Item類與實例實例變量@name@exam分別具有「揹包」和「只是揹包」的值:

a = [item] 
    #=> [#<Item:0x0000010201dda0 @name="Backpack", @exam="Just a backpack">] 

您可以使用Object#instance_variable_get檢索實例變量的值@name@exam,我將在局部變量存儲nameexam

name = a.first.instance_variable_get(:@name) #=> "Backpack" 
exam = a.first.instance_variable_get(:@exam) #=> "Just a backpack" 

現在,你有這些變量的值,你可以做無論你喜歡他們。

1

你可能想使用塊(假設你的項目類迴應。名稱和.exam選擇:

items = [#<Item:0x007faeea066508 @name="Backpack", @exam="Not much here... just a backpack">] 
item = items.select {|i| i.name =~ /backpack/i } 
puts item.exam 
0

這裏是我的代碼:

articles = ArticleType.all 

我的結果:

[#<ArticleType id: 1, name: "News", slug: "news">, #<ArticleType id: 2, name: "Articles", slug: "articles">] 

獲取第一個元素的名稱值:

articles[0].name 
=> "News" 

爲了讓您的數組名的值:

ArticleType.all.map(&:name) 

要獲取的元素包含 'N':

ArticleType.all.map { |x| puts x.name if x.name.include?('N') } 
=> News 

我希望它可以幫助你!

0

你可以做到這一點如下: -

user_typed_string = "examine backpack" 

items = [#<Item:0x007faeea066508 @name="Backpack", @exam="Not much here... just a backpack">] 

item = items.select {|i| user_typed_string.include?(i.name) }.last 

exam = item.exam unless item.nil?