官术网_书友最值得收藏!

Local variables

Local variables are variables whose scope is limited to the area where they are declared. In other words, if a local variable is declared inside a method or a loop, then its scope is limited to that method or loop.

For example, I am declaring a variable called x and asking it to be printed ten times inside a loop. This is how it will look:

10.times do 
x = 10
p x
end

You can now go to the Terminal and run this program. Before that, first check if you're in the right directory by typing the ls command and this will show the files in that directory. In this case, I've named my file as variable_types.rb and I can find this file in the list; and this means I'm in the right place.

Now, to check this code, you need to run the file, and you can do this with the following command:

ruby variable_types.rb  

This command will print the value ten times for you.

Now, what happens when you try to print the value of the x variable outside the loop? Logically, you would think x would have the value of 10, and this would be printed only once, since it's outside the loop:

10.times do 
x=10
end

p x

However, when you run the program, it throws an error:

This error occurs because x is a local variable that works only inside the loop and its value is unknown outside the loop. In other words, the system cannot tell you the value of x because it is not available outside the loop.

So, this is the scope of local variables.

主站蜘蛛池模板: 莒南县| 青州市| 花垣县| 扎囊县| 仁化县| 庆安县| 长子县| 贵州省| 开阳县| 日喀则市| 延庆县| 瑞昌市| 荣昌县| 陕西省| 仁寿县| 德钦县| 友谊县| 龙海市| 舞钢市| 嫩江县| 英超| 乌鲁木齐市| 乌鲁木齐市| 佳木斯市| 女性| 江城| 湖南省| 中山市| 玉山县| 玛纳斯县| 吉隆县| 乌兰浩特市| 沐川县| 鄯善县| 孟州市| 彩票| 龙陵县| 荥阳市| 织金县| 长岭县| 高邮市|