June 23, 2010

Ruby Variables and Constants

変数

例1

temperature = 34
puts temperature

Rubyの変数名

Rubyではキャメルケースより、アンダースコアが好みだそうです。
例えば変数名page_transfer_managerはOKだけど、pageTransferManagerはNG。

予約語

FILE def in self
LINE defined? module super
BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return yield

Example2

age = 99
puts "My age: " + String(age)
puts "My age: " + age.to_s
puts "My age: #{age} "

整数を文字列に変換することに注意してください。
ダブルクォーテーション内であれば任意の式を#{ }に入れることができます。

Constants

PI = 3.1415926535

コンスタントは大文字でスタートします。
これでRubyはコンスタントと認識してくれます。

English

Variable

Example1

temperature = 34
puts temperature

Ruby convention

To use underscores rather than "camel case" for multiple-word names.

page_transfer_manager is good, for example, but pageTransferManager is not.

Reserved words

FILE def in self
LINE defined? module super
BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return yield

Example2

age = 99
puts "My age: " + String(age)
puts "My age: " + age.to_s
puts "My age: #{age} "

Note that you need to convert the integer variable to string.
You can place any expression inside #{ and } in a double-quoted string
and have it interpolated into the text.

Constants

PI = 3.1415926535

Constants in Ruby start with an uppercase letter—that’s how Ruby
knows they are constants. In fact, the entire name of a constant is usually in uppercase. But it’s that first
letter that is crucial—it must be uppercase so that Ruby knows that you intend to create a constant.

Share on Twitter Share the post
Qihuan Piao

Qihuan Piao

(aka kinopyo) is Chinese based in Tokyo. Software writer. He shares stories inspired him in this blog. His infamous line - "I feel calm when I kill those monsters, or people (in game)" shocks his friends deeply.

He also writes in Japanese and Chinese.