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

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.

Don't worry if this sounds foreign to you. This is a more advanced development topic and I'm introducing it here so it will look familiar to you when you go through Rails applications. For now, I just want you to understand the scope of an instance variable and how it is different from local variables.
主站蜘蛛池模板: 连城县| 黑龙江省| 韩城市| 金昌市| 烟台市| 台江县| 佳木斯市| 阳山县| 酒泉市| 板桥市| 巴彦淖尔市| 白河县| 阿尔山市| 郧西县| 仙桃市| 邹城市| 钟山县| 永州市| 崇州市| 平舆县| 西华县| 咸丰县| 海伦市| 清涧县| 定西市| 扶风县| 拉萨市| 社旗县| 金溪县| 巴彦淖尔市| 霍邱县| 怀远县| 崇文区| 普安县| 庆元县| 临洮县| 武城县| 获嘉县| 收藏| 黔江区| 怀柔区|