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 比较两个集合
分享到:
相关推荐
《Programming Ruby - The Pragmatic Programmer's Guide》第二版(2005年注释版)是一本在IT行业中享有盛誉的经典书籍,专门针对Ruby编程语言进行了深入浅出的讲解。该书不仅覆盖了Ruby语言的基础知识,还探讨了其...
ruby 编程入门的 绝佳 书籍。本书主要包括四部分: 1. Facets of Ruby 2. Ruby in its setting 3. Ruby Crystallized 4. Ruby Library reference.
- **第一部分**:“面向Ruby的方方面面”(Facets of Ruby),介绍了Ruby的基本特性和编程范式。 - **第1章**:“开始使用Ruby”,从命令行环境入手,讲解了如何安装Ruby、运行Ruby程序以及如何使用Ruby文档工具如RDoc...
This book gets you started with essential software development easily and quickly, guiding you through Java's different facets. By adopting this approach, you can bridge the gap between learning and ...
2. **语言特性对比:** 本书将详细探讨Ruby与C#的语言特性差异,比如动态类型、块(Block)和元编程等Ruby特有的功能,以及它们如何影响程序设计方式。 3. **代码示例:** 书中提供了大量的代码示例,用以展示相同功能...
Improve your skills to become the next-gen network engineer by learning the various facets of Python programming Book Description Python is an excellent language to use to write code and have fun by ...
项目建筑师: 采取的是一个和Java8 Web开发框架。...import org.takes.facets.fork.FkRegex ;import org.takes.facets.fork.TkFork ;public final class App { public static void main ( final String ..
achieve interoperability and especially the integration of information about different facets of an enterprise application from multiple analysis tools, this specification defines several compliance ...
Step by step, you’ll learn to use C++ in all facets of real-world game programming, including 2D and 3D graphics, physics, AI, audio, user interfaces, and much more. You’ll hone real-world skills ...
Part 3: Generic Programming – Locales and Facets Part 3: Generic Programming – TextI/O Part 3: Generic Programming – Project3: Currency Type Part 4: Real Programming – Pointers Part 4: Real ...
List of Tables x List of Figures xiv 1 Scope 1 2 Normative references 2 3 Terms and definitions 3 4 General principles 7 4.1 Implementation compliance . . . . . . . . . . . . . . . . . . . . . . . . ....
5.1.3 I/O for Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 5.1.4 Conversions between tuple sandpairs . . . . . . . . . . . . . . . . . . 75 5.2 Smart Pointers . . . . . . ...
Improve your skills to become the next-gen network engineer by learning the various facets of Python programming Book Description Python is an excellent language to use to write code and have fun by ...
This book gets you started with essential software development easily and quickly, guiding you through Java's different facets. By adopting this approach, you can bridge the gap between learning and ...
"Facets Master" 是一个测试工具,主要用于业务流程测试。这个工具可能包含了多个组件和功能,以帮助用户高效地进行软件或系统的业务流程验证。在分析这个压缩包 "facets-master.zip" 的内容前,我们先来理解一下...
FACETS(Facets of Computerized Analysis for Tests and Test Examinations)软件是由美国威斯康星大学麦迪逊分校开发的一款专门用于分析多面Rasch模型的数据处理工具。它能够帮助研究者对大规模的主观评价数据进行...
9. **宝石(Gems)和加载机制**:Ruby的包管理器Gem允许开发者轻松地共享和使用元编程库,如`metaid`和`facets`。 10. **DSL设计**:Ruby的元编程能力使其成为构建DSL的理想选择。DSL可以简化复杂的任务,使代码更...
类似ASTROMESH结构的索网天线型面的成形原理为,用若干小平面去逼近理想抛物面反射面,小平面网格的尺寸大小以及节点位置直接影响着与理想抛物面的逼近程度。本文主要讨论对抛物面反射面用网格平面进行逼近时的最佳...
Ruby刻面 “您的所有基地都是Ruby”介绍Ruby Facets是Ruby编程语言的通用方法扩展和标准添加的首屈一指的集合。 Facets包含可用于扩展Ruby内置类和模块的核心功能的最大方法集。 这种扩展方法的集合由于其原子性而...