Вопрос

I'm a beginner at programming, and I'm trying to complete Zed Shaw's book for Ruby, and I just cannot understand the last for statement of the code. If the variables state and abbrev have not been defined, how does the software know where to get values for them?

states = {
    'Oregon' => 'OR',
    'Florida' => 'FL',
    'California' => 'CA',
    'New York' => 'NY',
    'Michigan' => 'MI'
}

cities = {
    'CA' => 'San Francisco',
    'MI' => 'Detroit',
    'FL' => 'Jacksonville'
}

for state, abbrev in states
    puts "%s state is abbreviated %s and has city %s" % [
        state, abbrev, cities[abbrev]]
end
Это было полезно?

Решение

Those variables are valid only within the for ... end iteration. It is similar to block variables such as x in a block {|x| .... x ...}. The values are assigned to each element of states, or, if it does not have a natural sense of an element, then to_a, will be applied. In the following, e is assigned an element of states,

for e in states
  ...
end

and change each time as it goes through the iteration. Since states is a hash, it will be an array of key-value pair like ['Oregon', 'OR'].

But there is one more complication to that; that is called destructive assignment. When the number of variables and the object does not match during assignment, Ruby tries to distribute them to make much sense as possible. In this case, you have state and abbrev, which are two variables, to be assigned a single array like ['Oregon', 'OR']. Ruby decomposes that array, and assigns its elements to each variable:

state # => "Oregon"
abbrev # => "OR"

Другие советы

The for-in construct in this case iterates through the states Hash; for each key-value pair, state is set to the key and abbrev is set to the value. So the first time through, state is set to 'Oregon' and abbrev is set to 'OR', then state is set to 'Florida' and abbrev is set to 'FL', and so on through the whole Hash. This is simply the way the for-in syntax is defined to work in Ruby.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top