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!'
No variable is ever declared in Ruby. Rather, the rule is that a variable must appear in an assignment before it is used. Again, the variable input is assigned before it is used in the puts call.
Ruby and Variable Dynamic Typing For example if the variable is required to store an integer value, you must declare the variable as an integer type. With such languages, when a variable has been declared as a particular type, the type cannot be changed. Ruby, on the other hand, is a dynamically typed language.
To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With