"数"不是声明的变量,但仍然有效?

时间:2014-12-18 10:04:51

标签: ruby

我正在学习ruby,我把这段代码写成了课程的一部分,但是在第9行引入了变量number但未声明,控制台没有抛出错误,为什么这是?它是for循环的具体部分吗?

#set an array counting up from 1 - 5 
the_count = [1, 2, 3, 4, 5]
#array of fruits
fruits = ['apples', 'oranges', 'pears', 'apricots']
#mixed array of numbers and currency
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# for each number in the_count array put... 
for number in the_count
    puts "this is count #{number}"
end

#for each element in the fruit array put...
fruits.each do |fruit|
    puts "a fruit of type: #{fruit}"
end

#iterate through each element in change and on each of them preceed its value with "i got"
change.each {|i| puts "I got #{i}"}

#create an empty array
elements = []

#interate through numbers 0 - 5 
(0..5).each do |i|
    puts "adding to #{i} to the list."
#push each number to empty array
    elements.push(i)
end

#iterate through each element in elements and preceed it with "Element was:"
elements.each {|i| puts "Element was: #{i}"}

1 个答案:

答案 0 :(得分:0)

在Ruby中,未声明变量。解释器决定令牌是变量,如果它被赋值,或者像这种情况一样,与for in语法一起使用。