Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables in Ruby?

Tags:

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!'
like image 294
Alex Wilsen Avatar asked Apr 26 '13 23:04

Alex Wilsen


People also ask

How do you define a variable in Ruby?

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.

How do you declare an integer variable in Ruby?

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.

How do you declare a variables?

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).


1 Answers

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.

like image 68
Gene Avatar answered Oct 25 '22 04:10

Gene