我正在尝试运行一个方法,将数字转换为字符串,在不同的基础上。
我使用下面的提示来弄清楚如何转换为不同的基础
#You will want to use the %, or modulus function; this finds the remainder when you divide by a number:
(123 / 10**0) % 10 == 3 # ones place
(123 / 10**1) % 10 == 2 # tens place
(123 / 10**2) % 10 == 1 # hundreds place
但是,当我运行脚本时,我收到错误
/Users/stepan/Desktop/ruby_tester.rb:33:in `block in num_to_s': undefined local variable or method `digit' for main:Object
但是,我认为我确实有一个名为digit的局部变量。我究竟做错了什么?
Digits = {
1 => "1",
2 => "2",
3 => "3",
4 => "4",
5 => "5",
6 => "6",
7 => "7",
8 => "8",
9 => "9",
10 => "10",
11 => "a",
12 => "b",
13 => "c",
14 => "d",
15 => "e",
16 => "f",
}
def num_to_s(num,base)
highest_power = 0
answer = " "
while base**highest_power < num
highest_power += 1
end
puts highest_power
for power in 0..highest_power do
digit = Digits[ ((num / base**power) % base) ]
answer.prepend(digit)
end
puts answer
end
num_to_s(10,2)
答案 0 :(得分:1)
在数字哈希中添加0:
0 => "0",
(10 / 2**0) % 2
评估为0
中无法找到的Digits
,因此将digit
设置为nil。
您的代码中还有其他问题(10 =&gt;'10'和11 =&gt;'a'?)以及更好的处理方法,但这应该可以解决这个问题。
答案 1 :(得分:1)
main:Object
运行代码,则通常会触发 rails console
个错误
只需使用
运行该文件$ruby /Users/stepan/Desktop/ruby_tester.rb
并且在@Matt的建议下,它将完美无缺地执行