命令行

从命令提示符运行Ruby, 输入源代码的文件名:
$ ruby my_sou­rce­-co­de.rb

交互式Ruby

交互式Ruby Shell可用于交互式编程:
$ irb
>>

加载文件

在IRB中, 文件可以使用load命令加载:
>> load 'scrip­t_n­ame.rb'

Input

获取字符串例如:
direction = gets.chomp

Indent­ation缩进

实用但不是必要的

If / Else Loops

if my_variable_is_true && my_other_variable_is_true
  dosomething
elseif !my_next_variable_is_false
  dosomethingelse
else
  dothis
end

for loop - next

next跳到下一个元素

Unless

unless my_variable_is_true
  # dosomething
end

Console output

使用puts显示输出。

Object methods

object_id
The object ID

数据类型

Boolean

true or false

numbers

strings

' or " quoted

数字方法

odd

even

字符串方法

*

重复字符串

length

字符串中的字符数

reverse

反向列出字符串

to_sym

转换为符号

字符串插值Interp­olation

可以用于在双引号字符串中插入变量值:
“String with interp­ola­tion: #{vari­abl­e_n­ame}”

运算

+

2+2

-

5-3

*

5*3

/

8/2

next

下一个数字

pred

前一个

逻辑运算符

&&

and

||

or

!

not

比较运算符

<

小于

>

大于

<=

小于或等于

>=

大于或等于

!=

不相等

范围

.. 从第一到最后
... from first to predec­essor before last

Symbols

Created using :
eg string­_test = :test_­symbol
More efficient than strings - only stored once

Symbol methods

to_s
To string

Arrays

Described in [] with items delimited by commas:
meal = ['brea­kfast', 'lunch', 'dinner']

Array methods

new
Create an array
<<
Append to the end of an array
empty?
Is array empty
shift
Remove front element from array
unshift
Add new element at front of array
pop
Remove element from end of array
push
Add element to end of array

Array loop

for my_placeholder in my_array
  next if something_is_true
  do_something
end

Array loop example 2

my_array.each do |my_placeholder|
  next if something_is_true
  do_something
end

Array loop example 3

my_array.each { |my_placeholder| next if something_is_true do_something }

Hashes

Contain key value pairs. Can use symbols for keys.

Hash methods

has_key?
Has the key
has_value?
Has the value
my_has­h[:­my_key] = my_value
Set has value

方法定义

def my_method(argument_1,
      argument_with_default = 1,
      *splat_argument)
  # method body
  # use return keyword to return a value
  # better practice to omit return keyword
  puts "argument_1: #{argument_1}"
  puts "argument_with_default: #{argument_with_default}"
  return splat.length
end

Yield in Blocks

The yield keyword is used to invoke a calling block from within a method. Control is passed back to the method after the block has been invoked.