Ruby Variable Scope 簡單講解

Name Begins With Variable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@ A class variable

以一個簡單例子示例各種變量的區別:

class Female
	# Constant
	SEX = 'female'

	# Class variable: shared among all instances of this class
	@@sex = SEX

	def initialize( weight, height)
		# Instance variable: accessible to specific instance of this class
		@weight = weight
		@height = height
	end

	def self.sex
		@@sex
	end

	def description
		# Local variable: local to this block
		ideal_weight = @height * 0.8

		puts 'This female ideal weight would be ' + ideal_weight.to_s + ' and her actually weight is ' + @weight.to_s
	end

end


puts Female.new(130, 170).description
puts Female.sex


Console中進入此文件所在文件夾,假設此文件名位test.rb,輸入 ruby test.rb 運行此文件,得到如下結果:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章