将返回值传递给另一个方法

时间:2015-08-05 16:19:08

标签: ruby

我从一系列字母开始:

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这样的块吗?我尝试了各种不断说错误的论点。

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

2 个答案:

答案 0 :(得分:3)

你走了,没有错误:

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

答案 1 :(得分:3)

我会写这样的东西:

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))