Programming Ruby (Part I. Facets of Ruby)

Getting Start

 

OS X Distributions

1, MacPorts: package management system

 

$ sudo port install ruby19
 

2, Building ruby from source, get source and do follow:

./configure
make
make test 
make install
 

Check which shell has been using, do follow:

 

echo $SHELL

 

if console display bin/bash , we should change inside of ~/.profile or ~/.bash_profile .

 

export PATH=/<path>:$PATH

 

/<path> :   => the path which you want to add into environment variable and use,  : to separate each path
$PATH        => previous paths which already have been added into

 

 

 

Ruby.new

 

1, Ruby is an Object-Oriented Language

 

The most common String object is to use string literals, which are sequences of characters between single or double quotation marks. The difference between the two forms is the amount of processing ruby does on the string while constructing the literal.

 

in single-quoted case, Ruby does very little.

 

in double-quoted case, Ruby does more work.
 i) it looks for substitutions (for example, " \n " => newline)
 ii) expression interpolation  (for example, "Good night, #{name} ")

 

The value returned by a Ruby method is the value of the last expression evaluated, so we can get rid of the temporary variable and return statement altogether.

 

Ruby uses a convention : the first characters of a name indicate how the name is used.
 i). Local variables, method parameters, and method names should all start with a lowercase or with an underscore.
 ii). Global variables are prefixed with a dollar sign($ ) and instance variables begin with an at sign(@ )
 iii). Class variables start with two at signs (@@ )
 iv). Class names, module names and constants must start with an uppercase letter.

 

2, Arrays and Hashes

 

arrays and hashes are indexed collections. with arrays, the key is an integer, whereas hashes support any object as a key.

in Ruby, nil is an object.

 

simple way to create array (for example : a = %w{ cat dog bee } same as a = [ 'cat', 'dog', 'bee' ]

 

Hash use braces rather than square brackets, and the literal must supply two objects for every entry: one for the key, the other for the value.

 

inst_section = { 
  'cello'    =>   'string',
  'drum'   =>   'percussion'
}

 

 

3, Symbols

 

Symbols are simply constant names that you don't have to pre declare and that are guaranteed to be unique. (for example :symbol_name )

symbols are so frequently used as hash keys in Ruby 1.9, you can use name : value pairs to create a hash if the keys are symbols.

inst_section = {
  :cello => 'string',
  :drum => 'percussion'
}

    在ruby 1.9里面, 可以不加:, 直接 cello => 'string'

 

 

4, Control Structures

 

Most statements in Ruby return a value, which means you can use them as conditions.

Ruby statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression. Simply write the expression, followed by if or while and the condition.

 

for example:

 

  if radiation > 3000
    puts "Danger, Will Robinson"
  end 

  puts "Danger, Will Robinson" if radiation > 3000
 

 

5, Regular Expressions

 

 

 

 

6, Blocks and Iterators

 

code blocks, which are chunks of code you can associate with method invocations, almost as if they were parameters.

{ } for single-line

do / end for multi-line

A method can then invoke an associated block one or more times using the Ruby yield statement. You can think of yield as being someting like a method call that invokes the block associated with the call to the method containing the yield.

 

You can provide arguments to the call to yield, and they will be passed to the block. Within the block, you list the names of the parameters to receive these arguments between vertical bars (| params |).

 

Code blcoks are used throughout the Ruby library to implement iterators.

 

 

7, Reading and 'Riting

 

puts writes its arguments with a newline after each; print also writes its arguments but with no newline. Both can be used to write to any I/O object, but by default they write to standard output.


printf , which prints its arguments under the control of a format string (just like printf in C or Perl)
printf : 对string的格式进行控制

 

 

8, Command-Line Arguments

the array ARGV contains each of the arguments passed to the running program.

 

 

 

Classes, Objects, and Variables

 

 

1, Objects and Attributes

 

Writing accessor methods is such a common idiom, Ruby provides a convenient shortcut. attr_reader creates these atrribute reader methods.

attr_reader :isbn, :price
 

you can think of :isbn as meaning the name isbn and plain isbn as meaning the value of the variable.

 

 

Virtual Attributes

 

2, Classes Working with Other Classes

 

require_relative because the location of the file we’re loading is relative to the file we’re loading it from (same directory)

 

CSV (Comma-separated Values) file is a simple text format for a database table.

CSV file format: "ISBN","14.99"   Note: there is NO space between comma.

 

 

3, Access Control

Ruby gives three levels of protection:

 i). Public methods: can be called by anyone. (except for initialize, which is always private)
 ii). Protected methods: can be invoked only by objects of the defining class and its sub-classes.
 iii). Private methods: can be called only in the context of the current object.

 

If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.

 

 

4, Variables

 

in Ruby, a variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of time) and are pointed to by variables.

Using the dup method of String, which creates a new String object with identical contents

for example:

 

  person1 = "Tim"
  person2 = person1.dup

person1 和 person2 创建了两个不同的String Object, 内容是相同的。



You can also prevent anyone from changing a particular object by freezing it.

for example:

 

  person1 = "Tim"
  person2 = person1
  person1.freeze
  person2[0] = "J"

 

There will be a RuntimeError

 

 

Containers, Blocks, and Iterators

Ruby comes with two built-in classes to handle collections: arrays and hashes. Mastery of these two classes is key to being an effective Ruby programmer .

Array

You can treat arrays as stacks, sets, queues, dequeues, and FIFO queues

for example:
  Stacks: use push and pop methods
  FIFO queues: use push and shift methods

 

 

Hash

 

You can index a hash with objects of any type: symbols strings regular expressions and so on.

 

the pattern [\w']+ : which matches sequences containing "word characters" and single quotes

 

 

Block

 

Block can appear in Ruby source code only immediately after the invocation of some method.

 

important rule: if there's a variable inside a block with the same name as a variable in the same scope outside the block, the two are the same.
在block内和外的变量名是重名的, 那么这两个变量是一样的

 

IN RUBY1.9: parameters to a block are now always local to a block, even if they have the same name as locals in the surrounding scope.

还要注意: 是参数和外部变量的名重合, 不会有问题,但是外部变量和内部变量重合, 就会有问题

 

A Block may also return a value to the method.

 

collect which takes each element from the collection and passes it to the block. the results returned by the block are used to construct a new array.   ( each, map 都可以返回数组 )

each_with_index : keep track of how many times you've been through the block.

inject : lets you accumulate a value across the memebers of a collection.

inject(:+)    inject(:*)

 

 

Enumerators -- External Iterators

 

Ruby 的外部迭代 & 内部迭代

一个基本的问题是决定到底由哪一方来控制迭代,是迭代器自身还是使用迭代器的客户代码?当客户代码控制迭代时,该迭代器被称为外部迭代器,反之当迭代器控 制迭代时,该迭代器就是一个内部迭代器。那些使用外部迭代器的客户代码必须负责推进整个遍历过程并且显式的从迭代器中获得下一个元素。相比之下,在使用内 部迭代器时,客户代码将一个操作传递给一个内部迭代器,该迭代器依次在每个元素上应用该操作。

外部迭代器比内部迭代器更灵活。比如,使用外部迭代器可以很容易的比较两个集合的相等性,如果用内部迭代器则不太可能。但是从另一个角度来看,内部迭代器更容易使用,因为它们已经为你定义好了迭代逻辑。

在Ruby中,像each这样的迭代器方法是内部迭代器,它们控制着迭代并且将值“推送”给那个与方法调用相关联的代码块。Enumerator 枚举器具有一个each方法,可用于内部迭代,但是在Ruby1.9及其后的版本里,它们还能充当外部迭代器,客户代码可以使用next方法顺序的从一个 枚举器中“取出"值。

 

loop 比较两个集合

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值