簡體   English   中英

將返回值傳遞給另一種方法

[英]Passing return value into another method

我從一系列字母開始:

letters = %w[c s t p b l f g d m  
             y o u i h t r a e l 
             o t l a e m r s n i 
             m a y l p x s e k d]

通過它們,找到所有返回數組的組合,例如["cstp", "cstb", "cstl"] ,這是一個簡化的示例。

def combinations(letters)
  combos = letters.combination(4) 
  combos.collect do |letter_set|
    letter_set.join(",").gsub("," ,"")  
  end
end

我試圖弄清楚如何將combinations的返回值傳遞給start_wtih_letter_c 我是否必須通過&block這樣的代碼&block 我嘗試了各種各樣的事情,不斷說錯論點。

def start_with_letter_c(pass the return value)
  combinations.select {|word| word.match(/^ca/) }
end

到這里,沒有錯誤:

letters = %w[c s t p b l f g d m  
             y o u i h t r a e l 
             o t l a e m r s n i 
             m a y l p x s e k d]

def combinations(letters)
  combos = letters.combination(4) 
  combos.collect do |letter_set|
    letter_set.join(",").gsub("," ,"")  
  end
end

def start_with_letter_c(combinations)
  combinations.select {|word| word.match(/^ca/) }
end

start_with_letter_c(combinations(letters))
# => ["cael", "caeo", "caet", "cael", "ca ...and so on

我會這樣寫:

letters = %w[c s t p b l f g d m  
             y o u i h t r a e l 
             o t l a e m r s n i 
             m a y l p x s e k d]

def combinations(letters)
  letters.combination(4).map(&:join) 
end

def start_with_letter_c(combinations)
  combinations.select { |word| word.start_with?('ca') }
end

start_with_letter_c(combinations(letters))

暫無
暫無

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

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