- 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.
- Bootstrap Site Blueprints Volume II
- Python量化投資指南:基礎(chǔ)、數(shù)據(jù)與實(shí)戰(zhàn)
- Java高并發(fā)核心編程(卷2):多線程、鎖、JMM、JUC、高并發(fā)設(shè)計(jì)模式
- 精通搜索分析
- 學(xué)習(xí)正則表達(dá)式
- Java編程的邏輯
- AIRIOT物聯(lián)網(wǎng)平臺(tái)開(kāi)發(fā)框架應(yīng)用與實(shí)戰(zhàn)
- JSP程序設(shè)計(jì)實(shí)例教程(第2版)
- Cocos2d-x Game Development Blueprints
- Microsoft HoloLens By Example
- JavaEE架構(gòu)與程序設(shè)計(jì)
- Node.js實(shí)戰(zhàn):分布式系統(tǒng)中的后端服務(wù)開(kāi)發(fā)
- Ubuntu Server Cookbook
- Instant Pygame for Python Game Development How-to
- 程序員的英語(yǔ)