- Comprehensive Ruby Programming
- Jordan Hudgens
- 248字
- 2021-07-02 21:13:24
Instance variables
As the name suggests, instance variables are available to a particular instance. There is a specific syntax to set instance variables, you need to use the @ sign to define a variable. For example, keeping in tune with our baseball theme, we can set the batting average like this:
@batting_average = 300
I'm going to show you how instance variables are used in a real-life Ruby on Rails application:

In the preceding code, you can see that there is an instance variable called @jobs. This variable is created in the index method and is not available to other methods in the file. Now, you may wonder why we wouldn't just make this a local variable since it's not available to other methods in the class.
The reason for this is because Rails is structured in such a way that the view and controller files are wired to communicate with each other, so this instance variable @jobs can be accessed in the associated view file. This is how the view file looks:

Now, @jobs is available for the view page only because we made it an instance variable in the controller file.
- 數(shù)據(jù)科學(xué)實(shí)戰(zhàn)手冊(cè)(R+Python)
- 深入淺出WPF
- 老“碼”識(shí)途
- 深入淺出DPDK
- C語言程序設(shè)計(jì)案例精粹
- 組態(tài)軟件技術(shù)與應(yīng)用
- 機(jī)器學(xué)習(xí)與R語言實(shí)戰(zhàn)
- 編寫高質(zhì)量代碼:改善Objective-C程序的61個(gè)建議
- Android應(yīng)用開發(fā)實(shí)戰(zhàn)
- ASP.NET求職寶典
- STM8實(shí)戰(zhàn)
- Qt 4開發(fā)實(shí)踐
- Python大規(guī)模機(jī)器學(xué)習(xí)
- 從零開始學(xué)UI:概念解析、實(shí)戰(zhàn)提高、突破規(guī)則
- Java RESTful Web Service實(shí)戰(zhàn)