---
title: "类中的成员变量可以这样声明， 但访问不能用@"
author: "lemonzc"
date: "2007-12-21T17:33:03Z"
tags: ["ActiveRecord", "Bean", "Ruby"]
slug: "untitled"
draft: false
lastmod: "2007-12-21T17:33:03Z"
id: 150035
url: "https://lemonzc.iteye.com/blog/150035"
---

大家先看下面代码：

```

class Person < Struct.new(:age)
	def say_age
		puts "say age: #{age}" if age != nil
	end
	
	def hello_age
		puts "hello age: #{age}" if age!=nil
	end
end

p = Person.new(30)

p.say_age
p.hello_age

p.age = 20
p.say_age
p.hello_age

```


输出是：
say age: 30
hello age: 30
say age: 20
hello age: 20

如果使用:


```

	def say_age
		puts "say age: #{@age}" if @age != nil
	end
	
	def hello_age
		puts "hello age: #{@age}" if @age!=nil
	end

```

那么什么都不输出，应为@age 为nil

如果使用:

```

	def say_age
		puts "say age: #{:age}" if :age != nil
	end
	
	def hello_age
		puts "hello age: #{:age}" if :age!=nil
	end

```

那么输出是：
say age: age
hello age: age
say age: age
hello age: age

:age 符号而已

ActiveRecord的低层有使用这种方式申明class


```

class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
..
..
..
end

```


文件：schema_definitions.rb
路径:%RUBY_HOME%\\lib\ruby\gems\1.8\gems\activerecord-2.0.1\lib\active_record\connection_adapters\abstract