我如何使用数组方法?

时间:2015-07-19 05:30:34

标签: ruby-on-rails ruby

我理解数组以组织方式包含数据,并且您可以向它们追加,删除等。但是,我不确定如何构建代码或者我是否正确理解这些代码。

任务:

describe "no_fruits?" do
  it "returns false for non-empty array" do
    ary = ["apple", "banna"]
    expect( no_fruits?(ary) ).to eq(false)
  end

  it "returns true for empty array" do
    ary = []
    expect( no_fruits?(ary) ).to eq(true)
  end
end

describe "number_of_fruits" do
  it "returns the number of fruits" do
    ary1 = ["apple", "banana"]
    ary2 = ["apple", "papaya", "kiwi"]
    expect( number_of_fruits(ary1, ary2) ).to eq(5)
  end
end

describe "number_of_unique_fruits" do
  it "returns the number of unique fruits in an array with duplicates" do
    expect( number_of_unique_fruits(["apple", "apple", "banana", "kiwi"]) ).to eq(3)
  end

  it "returns the number of unique fruits in an array without duplicates" do
    expect( number_of_unique_fruits(["apple", "banana", "papaya", "kiwi"]) ).to eq(4)
  end
end

到目前为止我的尝试:

def no_fruits?(a)
 if a 
   false
else (a.empty?)
  true
   end
end

def number_of_fruits(a1, a2)
  a1=["apple", "banana"]
  a2=5
end

def number_of_unique_fruits()
  number_of_unique_fruits.uniq
  number_of_unique_fruits.uniq!
end

3 个答案:

答案 0 :(得分:1)

实际上我并没有完全理解你的任务,但是从我的代码中我认为它应该是这样的:

def no_fruits?(a)
  a.empty?
end

def number_of_fruits(a1, a2)
  a1.count + a2.count
end

def number_of_unique_fruits(a)
  a.uniq.count
end

最后一个方法也应该接收一个数组。请试试这个。

希望这有帮助。

答案 1 :(得分:1)

def no_fruits?(*arrays)
  arrays.flatten.empty?
end

def number_of_fruits(*arrays)
  arrays.flatten.count
end

def number_of_unique_fruits(*arrays)
  arrays.flatten.uniq.count
end

*arrays参数前面的奇怪小字符称为the splat operator。它收集传递给数组中方法的任何剩余参数。通过使用它,我们的方法现在可以处理任何可能数量的果味数组。

所以如果我们打电话:

number_of_fruits(['apple'], ['pear'],['orange', 'plum'])

arrays参数等于:

[['apple'], ['pear'],['orange', 'plum']]

然后我们使用Array#flatten,它接受​​一个数组数组并递归地展平它们:

irb(main):006:0> [['apple'], ['pear'],['orange', 'plum']].flatten
=> ["apple", "pear", "orange", "plum"]

答案 2 :(得分:0)

试试这个

def no_fruits?(a)
  a.empty?
end

def number_of_fruits(a1, a2)
  number_of_unique_fruits(a1) + number_of_unique_fruits(a2) 
end

def number_of_unique_fruits(a)
  a.uniq.count
end

正如Deep所说,最后一个方法应该接收一个数组。