2014-11-23 35 views
1

我正在研究一个ruby挑战,要求我创建一个输入字符串数组并将字符串分隔成3个类别作为符号返回的方法。这些符号将返回一个数组。Ruby:将数组解析为类别,返回符号

  • 如果字符串包含单词“猫”,则返回符号 :cat

  • 如果“狗”,则返回:dog.

  • 如果字符串不包含“狗”或“猫”则返回符号 :none

到目前为止,我有下面的代码,但无法通过。

def pets (house) 
    if house.include?/(?i:cat)/ 
    :cat = house 
    elsif house.include?/(?i:dog)/ 
    :dog = house 
    else 
    :none = house 
    end 
end 

input = [ "We have a dog", "Cat running around!", "All dOgS bark", "Nothing to see here", nil ]

它应该返回[ :dog, :cat, :dog, :none, :none ]

回答

1

我很惊讶,没有人去为case/when方法,所以在这里它是:

def pets(house) 
    house.map do |item| 
    case item 
     when /dog/i 
     :dog 
     when /cat/i 
     :cat 
     else 
     :none 
    end 
    end 
end 

map并不复杂:你使用它时,你有ň数组元素,你想变成另一个数组n元素。

我怀疑人们不会使用case/when,因为他们不记得语法,但它是专为这种情况设计的,当你测试一个项目对多个选择。它比if/elsif/elsif语法更加简洁,恕我直言。

+0

这真的很好,效率非常高。谢谢托德! – shroy 2014-11-28 23:56:23

+0

不客气!很高兴它对你有效。 – 2014-11-29 00:01:18

1
def pets (house) 
    results = [] 
    house.each do |str| 
    if str.to_s.downcase.include?('dog') 
     results << :dog 
    elsif str.to_s.downcase.include?('cat') 
     results << :cat 
    else 
     results << :none 
    end 
    end 
    return results 
end 

这工作。这里是上面的代码,用伪代码(纯英文,遵循类似代码的思考过程)编写,所以你可以看到我是如何得到上述解决方案的。

def pets (house) 
    # Define an empty array of results 
    # 
    # Now, loop over every element in the array 
    # that was passed in as a parameter: 
    # 
    # If that element contains 'dog', 
    #  Then add :dog to the results array. 
    # If that element contains 'cat' 
    #  Then add :cat to the results array 
    # Otherwise, 
    #  Add :none to the results array 
    #   
    # Finally, return the array of results. 
end 

有你似乎是在没有相当扎实几个概念 - 我不认为我能在合理的长度内有效地在这里解释它们。如果可能的话,试着看看你是否能遇到一位有经验的程序员面对面地解决这个问题 - 这将比试图自己解决问题要容易得多。

+0

制定出十分感谢! – shroy 2014-11-23 22:01:31

+0

另一个使用'map'方法的答案,实际上是一种更习惯于使用ruby的方法。不过,我认为地图方法的理解更加复杂,需要了解更多的编程概念。所以,我保持简单。 – 2014-11-23 22:04:21

1

这是一个使用Array#map方法的解决方案。

def pets (house) 
    house.map do |animal| 
     if animal.to_s.downcase.include?('cat') 
      :cat 
     elsif animal.to_s.downcase.include?('dog') 
      :dog 
     else 
      :none 
     end 
    end 
end 
0

你可以使用的匹配钥匙,和结果值的散列,具体如下:

ma = [ :cat, :dog ] 
input = [ "We have a dog", "Cat running around!", "All dOgS bark", "Nothing to see here", nil ] 
input.map {|s| ma.reduce(:none) {|result,m| s.to_s =~ /#{m}/i && m || result } } 
# => [:dog, :cat, :dog, :none, :none]