Learning Ruby 1 Ruby.new

with <Programming Ruby 2nd>
Ruby Basic

                   Variables        &nb[-aa--]sp;          Constants and
Local          Global        Instance Class    Class Names
name           $debug        @name    @@total  PI

fish_and_chips $CUSTOMER     @point_1 @@symtab FeetPerMile
x_axis         $_            @X       @@N      String
thx1138        $plan9        @_       @@x_pos  MyClass
_26            $Global       @plan9   @@SINGLE JazzSong

statement modi?ers
puts "Danger, Will Robinson" if radiation > 3000
square = square*square while square < 1000

Regular Expressions
In Ruby, you typically create a regular expression by writing a pattern
between slash characters (/pattern/).

This pipe character means “either the thing on the right or the thing on the left,” in this case either Perl or Python.
 /ab+c/ matches a string containing an a followed by one or more b’s, followed by a c.
/ab*c/ creates a regular expression that matches one a, zero or more b’s, and one c.

s, which matches a whitespace character (space, tab, newline, and so on);
d, which matches any digit;
w, which matches any character that may appear in a typical word.
A dot ( . ) matches (almost) any character.

if line =~ /Perl|Python/

line.sub(/Perl/, ‘Ruby’)    # replace first ‘Perl’ with ‘Ruby’
line.gsub(/Python/, ‘Ruby’) # replace every ‘Python’ with ‘Ruby’

Blocks and Iterators
{ puts "Hello" }      # this is a block
do                    ###
  club.enroll(person)   # and so is this
  person.socialize      #
end                   ###

    def call_block
      puts "Start of method"
      puts "End of method"
    call_block { puts "In the block" }
    Start of method
    In the block
    In the block
    End of method

def call_block
  yield("hello", 99)
call_block {|str, num| … }

iterators: methods that return successive elements from some kind of collection, such as an array.
   animals = %w( ant bee cat dog elk )  # create an array
   animals.each {|animal| puts animal } # iterate over the contents
# within class Array…
def each
  for each element    # <– not valid Ruby

Reading and ’Riting
puts writes its arguments, adding a newline after each.
print also writes its arguments, but with no newline.
printf, which prints its arguments under the control of a format stringejfkldfjai

转载请注明: 转自船长日志, 本文链接地址: http://www.cslog.cn/Content/learning-ruby-1-ruby-new/

此条目发表在 Ruby on Rails 分类目录。将固定链接加入收藏夹。


电子邮件地址不会被公开。 必填项已用 * 标注


您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>