Alex Wilsen
Alex Wilsen

Reputation: 265

Declaring variables in Ruby?

When do I know when to declare a variable and not to in Ruby?

I would like to know why the first code needs input to be declared as a string and outside of the block, while the second block doesn't.

input = ''
while input != 'bye'
  puts input
  input = gets.chomp
end
puts 'Come again soon!'

versus:

while true
  input = gets.chomp
  puts input 
  if input == 'bye'
    break 
  end
end
puts 'Come again soon!'

Upvotes: 26

Views: 56858

Answers (1)

Gene
Gene

Reputation: 47020

No variable is ever declared in Ruby. Rather, the rule is that a variable must appear in an assignment before it is used.

Look at the first two lines in your first example:

input = ''
while input != 'bye'

The while condition uses the variable input. Therefore the assignment is necessary before it. In the second example:

while true
  input = gets.chomp
  puts input 

Again, the variable input is assigned before it is used in the puts call. All is right with the world in both examples.

Upvotes: 37

Related Questions