Ruby 在函数中调用数组
Ruby calling an array in a function
尝试从函数中调用一个数组 assert_equal
以确保它返回预期的字符串。
这是我的函数:
def array_mod
a = *(1..100)
a.each { |i| if i % 3 == 0 && i % 5 == 0; i = "fifteen" elsif i % 3 == 0; i = "three" elsif i % 5 == 0; i = "five" else i = i end }
end
这是我尝试调用它的尝试。
require "minitest/autorun"
require_relative "array_modulus.rb"
class TestArrayFunction < Minitest::Test
def test_array1
results = array_mod
assert_equal(100, results.length)
end
def test_array2
results = array_mod
assert_equal("three", results[2])
end
end
测试通过 results.length
,但 returns "three"
作为 3
,一个整数。
我知道我可以创建一个数组并像这样
def abc
arr = []
*(1..100) do |i|
if i % 3 == 0
i = "three"
else
i = I
end
不过我很好奇用之前的写法能不能做到
抱歉有任何错误,我在 phone 上写了这个。
方法的值是方法中计算的最后一个表达式。在你的例子中,它是 a.each {...}
。这个方法总是returnsa
.
实际上,我不清楚你打算用 each
块做什么,因为它唯一做的就是改变块内的局部变量 i
,而这并没有不会影响块外的任何东西。
因此,您的方法等同于
def array_mod
(1..100).to_a
end
您想使用地图。试试这个:
def array_mod
a = *(1..100)
a.map do |i|
if i % 3 == 0 && i % 5 == 0
"fifteen"
elsif i % 3 == 0
"three"
elsif i % 5 == 0
"five"
end
end
end
尝试从函数中调用一个数组 assert_equal
以确保它返回预期的字符串。
这是我的函数:
def array_mod
a = *(1..100)
a.each { |i| if i % 3 == 0 && i % 5 == 0; i = "fifteen" elsif i % 3 == 0; i = "three" elsif i % 5 == 0; i = "five" else i = i end }
end
这是我尝试调用它的尝试。
require "minitest/autorun"
require_relative "array_modulus.rb"
class TestArrayFunction < Minitest::Test
def test_array1
results = array_mod
assert_equal(100, results.length)
end
def test_array2
results = array_mod
assert_equal("three", results[2])
end
end
测试通过 results.length
,但 returns "three"
作为 3
,一个整数。
我知道我可以创建一个数组并像这样
def abc
arr = []
*(1..100) do |i|
if i % 3 == 0
i = "three"
else
i = I
end
不过我很好奇用之前的写法能不能做到
抱歉有任何错误,我在 phone 上写了这个。
方法的值是方法中计算的最后一个表达式。在你的例子中,它是 a.each {...}
。这个方法总是returnsa
.
实际上,我不清楚你打算用 each
块做什么,因为它唯一做的就是改变块内的局部变量 i
,而这并没有不会影响块外的任何东西。
因此,您的方法等同于
def array_mod
(1..100).to_a
end
您想使用地图。试试这个:
def array_mod
a = *(1..100)
a.map do |i|
if i % 3 == 0 && i % 5 == 0
"fifteen"
elsif i % 3 == 0
"three"
elsif i % 5 == 0
"five"
end
end
end