- Comprehensive Ruby Programming
- Jordan Hudgens
- 311字
- 2021-07-02 21:13:23
Global variables
A global variable is a variable that is available for the entire application to use, and this is denoted by a $ preceding the variable. Now, if you apply the same code, you can see that x is printed. This is how the code should look:
10.times do
$x = 10
end
p $x
Now, if you run it in the console, it prints a value of 10.
Though this looks easy, using global variables is not a good idea. In my entire life, I think I've probably used a global variable only once, and now thinking back, I see that there could have been a better way to do it. In general, a global variable is not used because it is hard to track the value of these variables.
Let me give you a scenario. Let's create two files, namely, File1 and File2. In File1, let's assume we have a long algorithm and I create a global variable as a part of this algorithm. For presentation purposes, this is a baseball game and I have my global variable set to Yankees:
$global_var = "Yankees"
Say another developer who is working on this baseball application with me is working on File2. As a part of his algorithm, he also creates a global variable, but sets it to Astros. So, in File2, we have this code:
$global_var = "Astros"
So, when someone runs this program, the last file that gets loaded sets the value for this global variable. Also, the developer who created File1 has no idea that the value of global variable was altered to Astros in another file. So, the output will not be what he expects and overall, it can lead to a lot of confusion. This is why it's always a good idea to use variables that have limited scope, such as local or instance variables.
- PHP動態(tài)網(wǎng)站程序設(shè)計
- Visual Basic程序開發(fā)(學(xué)習(xí)筆記)
- NLTK基礎(chǔ)教程:用NLTK和Python庫構(gòu)建機器學(xué)習(xí)應(yīng)用
- 老“碼”識途
- Linux環(huán)境編程:從應(yīng)用到內(nèi)核
- Visual Basic學(xué)習(xí)手冊
- JavaScript入門經(jīng)典
- 自然語言處理Python進階
- 精通MATLAB(第3版)
- 編寫高質(zhì)量代碼:改善Objective-C程序的61個建議
- 新印象:解構(gòu)UI界面設(shè)計
- RocketMQ實戰(zhàn)與原理解析
- ActionScript 3.0從入門到精通(視頻實戰(zhàn)版)
- 30天學(xué)通C#項目案例開發(fā)
- Arduino電子設(shè)計實戰(zhàn)指南:零基礎(chǔ)篇