Chapter 2 : Ruby.new

一、Ruby is an object-oriented language
  1. a class is a combination of state and methods that use that state
  2. the world object   is used interchangeablely with class instance
  3. in Ruby, these objects are created by calling a constructor, a special method associated with a class ,the standard constructor is called new.

  4. every object has a unique object identifier (abbreviated as object ID), and instance vaviables with values that are unique to each instance.
  5. within each class, define instance methods. Each method is a chunk of functionality that may be called in the context of the class and (depending on accessibility constraints) from outside the class. 
  6. methods are invoked by sending a message to an object.
  7.         in Ruby, the ability to determine an absolute value is built into numbers—they take care of the details internally [内建或是内构 == to be continued!!]

二、Some Basic Ruby
1.    don't need semicolons at the ends of  statements as long as you put each statement on a separate line.
2.    methods are defined with the keyword def,   simply finish the body with  the keyword end.

3.    we didn't have to declare the variable, it sprang into existence when we assigned to it. [无需声明变量,在赋值给未声明的变量时ruby自动声明变量]

4.    Ruby string objects

        Ruby has many ways to create a string object, but probably the most common is to use string literals, which are sequences of characters between single or double quotation marks.

5.    expression interpolation [行内插值] 双引号字符串 within the string, the sequence #{expression} is replaced by the value of expression. arbitrarily complex expressions are allowed in the #{...} construct.

6.    the value returned by a Ruby method is the value of the last expression evaluated. [Ruby返回最后一行表达式结果]

7.    the first characters of a name indicate how the name is used .
(1) Local variables, method parameters, and method names should all  start with a lowercase letter  or an underscore.    局部变量,方法参数和方法名称的命名:以小写字母开头或是下划线开头

(2)Global variables are prefixed with a dollar  sign ($).  全局变量以 $ 符号开头

(3)instance variables begin with an “at” sign (@). 实例变量以 @ 符号开头

(4)Class variables start with two“at” signs (@@). 类变量以 @@ 符号开头

(5)class names, module names, and constants must start with an uppercase letter. 类名,模块名和常量必须以大写字母开头

(6)by convention, multiword instance variables are written with underscores between the words, and multiword class names are written in MixedCase (with each word capitalized),

    Method names may end with the characters ?, !, and =.

三、Arrays and Hashes

1. Ruby's arrays and hashes are indexed collections.Both store collections of objects, accessible using a key.

    With arrays, the key is an integer, whereas hashes support any object as a key.

2. You can create and initialize a new array object using an array literal—a set of elements between square brackets.

3. In many languages, the concept of nil(or null) means 'no object'. In Ruby, that's not the case; nil is an object, just like any other, that happens to represent nothing.

4. Ruby has a shortcut, %w does just what we want:

a = ['ant','bee','cat','dog','elk']
a[0] # => "ant"
a[3] # => "dog"
# this is the same:
a =%w{ ant bee cat dog elk }
a[0] # => "ant"
a[3] # => "dog"

A hash literal uses braces rather than square brackets. The literal must supply two objects for every entry: one for the key, the other for the value.
The key and value are normally separated by=>.

inst_section = {
'cello' =>'string',
'clarinet' =>'woodwind',
'drum' =>'percussion',
'oboe' =>'woodwind',
'trumpet' =>'brass',
'violin' =>'string'
}
Keys in a particular hash must be unique; you can't have two entries for 'drum.'

Hashes are indexed using the same square bracket notation as arrays. 

a hash by default returns nil when indexed by a key it doesn't contain.

This is easily done by specifying a default value when you create a new, empty hash.

histogram = Hash.new(0) # The default value is zero
histogram['ruby']# => 0
histogram['ruby'] = histogram['ruby'] + 1
histogram['ruby']# =>1

四、Symbols

 Symbols are simply constant names that you don't have to predeclare and that are guaranteed to be unique. A symbol literal starts with a colon and is normally followed by some kind of  name:

 There’s no need to assign some kind of value to a symbol.

 Ruby also guarantees that no matter where it appears in your program, a particular symbol will have the same value.
 Symbols are frequently used as keys in hashes.We could write our previous example as this:

inst_section = {
:cello =>'string',
:clarinet =>'woodwind',
:drum =>'percussion',
:oboe =>'woodwind',
:trumpet =>'brass',
:violin =>'string'
}
inst_section[:oboe] # => "woodwind"
inst_section[:cello] # => "string"
# Note that strings aren't the same as symbols...
inst_section['cello'] # => nil
In fact, symbols are so frequently used as hash keys that Ruby has a shortcut syntax:you can use name: value pairs to create a hash if the keys are symbols:
inst_section = {
cello: 'string',
clarinet:'woodwind',
drum: 'percussion',
oboe: 'woodwind',
trumpet: 'brass',
violin: 'string'
}
puts"An oboe is a#{inst_section[:oboe]}instrument"
五、Control Structures

1.Ruby uses the key word end to signify the end of a body of all the control structures

today = Time.now
if today.saturday?
puts "Do chores around the house"
elsif today.sunday?
puts "Relax"
else
puts"Go to work"
end

the kernel method gets returns the next line from the standard input stream or nil when the end of the file is reached.

Ruby statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression.

if radiation > 3000
  puts"Danger, Will Robinson"
end
#Here it is again, rewritten using a statement modifier:
puts "Danger, Will Robinson" if radiation > 3000
六、Regular Expressions

Most of Ruby's built-in types will be familiar to all programmers. A majority of languages have strings, integers, floats, arrays, and so on. However, regular expression support is
typically built into only scripting languages, such as Ruby, Perl, and awk.

This is a shame, because regular expressions, although cryptic, are a powerful tool for working with text. And having them built in, rather than tacked on through a library interface, makes a big difference.

1. A regular expression is simply a way of specifying a pattern of characters to be matched in a string.

In Ruby, you typically create a regular expression by writing a pattern between slash characters (/pattern/). And, Ruby being Ruby, regular expressions are objects and can
be manipulated as such.

2. The match operator=~can be used to match a string against a regular expression.

If the pattern is found in the string, =~returns its starting position; otherwise, it returns nil.

line = gets
  if line =~ /Perl|Python/
  puts "Scripting language mentioned:#{line}"
end
The part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:
line = gets
newline = line.sub(/Perl/,'Ruby') # replace first 'Perl' with 'Ruby'
newerline = newline.gsub(/Python/,'Ruby')# replace every 'Python' with 'Ruby'
七、Blocks and Iterators

This section briefly describes one of Ruby's particular strengths.

We're about to look at code blocks, which are chunks of code you can associate with method invocations, almost as if they were parameters

 “This is pretty interesting and important, so if you weren't paying attention before, you should probably start now.”

You can use code blocks to implement callbacks (but they're simpler than Java's anonymous inner classes), to pass around chunks of code (but they're more flexible than C's function
pointers), and to implement iterators.
Code blocks are just chunks of code between braces or between do and end.

use braces for single-line blocks and do/end for multiline blocks.

All you can do with a block is associate it with a call to a method. You do this by putting the start of the block at the end of the source line containing the method call.

greet { puts "Hi" }
verbose_greet("Dave","loyal customer") { puts "Hi" }
A method can then invoke an associated block one or more times using the Ruby yield statement. You can think of yield as being something like a method call that invokes the block
associated with the call to the method containing the yield.

def call_block
  puts"Start of method"
  yield
  yield
  puts "End of method"
end
call_block { puts "In the block" }
produces:
Start of method
In the block
In the block
End of method
You can provide arguments to the call to yield, and they will be passed to the block.
def who_says_what
  yield("Dave","hello")
  yield("Andy","goodbye")
end
who_says_what {|person, phrase| puts "#{person} says #{phrase}" }
produces:
Dave says hello
Andy says goodbye

Code blocks are used throughout the Ruby library to implement iterators, which are methods that return successive elements from some kind of collection, such as an array:

animals = %w( ant bee cat dog )       # create an array
animals.each { |animal| puts animal } # iterate over the contents
produces:
ant
bee
cat
dog
八、Reading and 'Riting

We've already come across two methods that do output:
puts writes its arguments with a newline after each;
print also writes its arguments but with no newline.
Another output methodweuse a lot is printf, which prints its arguments under the control of a format string (just like printf in C or Perl):

printf("Number: %5.2f,\nString: %s\n", 1.23,"hello")
produces:
Number: 1.23,
String: hello
You have many ways to read input into your program. Probably the most traditional is to use the method gets, which returns the next line from your program's standard input stream:
while line = gets
  print line
end
九、Command-Line Arguments 【待续】

十、Onward and Upward 向前,向前!!!

That's it. We've finished our lightning-fast tour of some of the basic features of Ruby.We took a look at objects, methods, strings, containers, and regular expressions; saw some simple

control structures; and looked at some rather nifty(小巧的) iterators. We hope this chapter has given you enough ammunition(弹药) to be able to attack the rest of this book.

嗯,我已就绪...尽情虐我吧!

你可能感兴趣的:(new,Ruby)