2012-04-26 77 views
0

我不知道該怎麼說,但我正在嘗試定義許多變量,然後重新定義它們而不重寫每一個變量,並在每個新塊中創建冗餘代碼。這些變量定義了來自多個數據庫的數組元素。這裏是我正在使用的一個縮小的示例:Ruby:(重新)從另一個塊/方法定義變量?

def lots_of_vars(array) 
    name = array[1] 
    membership = array[2] 
    spouse = array[3] 
    .... 
    lap12 = array[36] 
end 

def second_block 
    #database1 => [ "Randy", true, "Nancy", 2, 17, false... 
    lots_of_vars(database1) 
    return unless membership 
    puts "Lap progress for #{name} and #{spouse}: #{lap1}, #{lap2}... #{lap12}..." 
end 

def third_block 
    #database2 => [ "Steven", true, nil, 0, 5, false... 
    lots_of_vars(database2) 
    return unless spouse.empty? or spouse.nil? 
    puts "Weekly progress for #{name}: #{lap1}, #{lap5}, #{lap6}, #{lap10}..." 
end 

第二個和第三個塊需要從第一個塊/方法定義的所有變量。但是,我如何通過所有這些變量?我讀了一個例子,建議我通過他們的作爲參數,如:

def second_block(name, membership, spouse...) 

但這會使一樣多亂作爲兩個塊定義兩次,每次變量。對於這種情況,簡單幹燥的方法是什麼? 如果我需要澄清我的問題中的任何內容,請讓我知道,謝謝。

回答

3

你想要的是創建一個Struct,這是一個簡單的類來表示一個數據結構。一個結構將其論點的位置,這是你想要什麼,因爲你可以圖示的數組方法調用(把一個數組的參數列表)

所以

Thing = Struct.new(:name, :membership, :spouse, :lap12) 

array = ['Larry', 'gold', 'Sue', 2.2] 
thing = Thing.new(*array) 

#note that the splat (*) is equivalent to saying 
# Thing.new(array[0], array[1], array[2], array[3]) 

thing.name # => "Larry" 
thing.lap12 # => 2.2 
+0

謝謝,需要這個工作完全。 – rubyuser1357796 2012-04-26 18:06:00

0

絕對方法與結構是最好的之一。

而且你可以做這樣的事情:

這裏作野狗,不要嘗試在家裏! :)

class Foo 

    def lots_of_vars(array) 
    name = array[0] 
    email = array[1] 
    description = array[2] 

    binding 
    end 

    def bar 
    array = ['Luke', '[email protected]', 'Lorem ipsum'] 
    eval('"My name is #{name}, email: #{email}, here is description: #{description}"', lots_of_vars(array)) 
    end 

end 

foo = Foo.new 
foo.bar 

有關詳細信息,你可以檢查這個漂亮的博客文章關於Ruby的bindinghttp://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc

+0

感謝您的資源。很有幫助。 – rubyuser1357796 2012-04-26 18:06:24

+0

沒有問題,但請保證我不會在你的應用程序中使用'binding'技術;) – luacassus 2012-04-26 19:02:50

相關問題