Ruby on Rails的安装

08:44下午 六月 26, 2008 in category Ruby语言 by Ruby-红宝石

现在是初学Rbuy,在Windows下安装Ruby 和 Rails,到 http://www.rubyonrails.org/下载Rbuy和Rails。

先安装Ruby,按我的理解这个东东就相当于JDK了。我下载的是已经编译好的二进制包 One-Click Installer - Windows,安装就非常简单了,按提示安装就可以了。注意,默认的路径是C:\ruby,如果你自己指定目录,切记目录名称不要有空格!

现在安装 Rials,Rails有点相当于Tomcat,一个可以运行rbuy语言的web服务器。下载 rails-2.1.0.zip ,解压即可,例如放在D:\rails下。rials下的目录结构:

2008-06-26  15:15    <DIR>          .
2008-06-26  15:15    <DIR>          ..
2008-06-26  15:15    <DIR>          app
2008-05-31  19:01           101,375 CHANGELOG
2008-06-26  15:15    <DIR>          components
2008-06-26  15:15    <DIR>          config
2008-06-26  15:15    <DIR>          db
2008-06-26  15:15    <DIR>          doc
2008-06-26  15:15    <DIR>          lib
2008-06-26  20:20    <DIR>          log
2008-06-26  15:49    <DIR>          public
2008-05-31  19:01               307 Rakefile
2008-05-31  19:01            10,619 README
2008-06-26  20:20    <DIR>          script
2008-06-26  20:19    <DIR>          test
2008-06-26  15:15    <DIR>          tmp
2008-06-26  15:15    <DIR>          vendor

这个包,config\enviroment.rb里有点错误,需要修改。第8行内容如下:

<%= '# ' if freeze %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION

<%= '# ' if freeze %>这个是多余的,需要去掉。

第50行,不是错误,需要设置session的key和加密码:

  config.action_controller.session = {
    :session_key => '_<%= app_name %>_session',
    :secret      => '<%= app_secret %>'
  }

改成

  config.action_controller.session = {
    :session_key => 'myweb_session',
    :secret      => '123456789012345678901234567890'
  }

session_key自己随意定义,secret字符串要大于30个字符长度。

config\database.yml里要设置一下mysql的帐号和密码,否则点击

About your application’s environment 这个连接会出错。

这个就不多说了。

进入 D:\rails目录,运行 ruby script\server 及启动服务器了。

打开浏览器,输入  http://localhost:3000 就能看到网页了。

评论[0]

Ruby的后续文章请参照本文地址

03:50下午 三月 18, 2008 in category Ruby语言 by Ruby-红宝石

http://www.rubyist.net/~slagell/ruby/

评论[0]

Ruby 重温前面的例子

03:49下午 三月 18, 2008 in category Ruby语言 by Ruby-红宝石

返回前面的简单示例

现在让我们看看前面例子程序的部分代码。

下面的代码出现在前面的示例章节。

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end
puts fact(ARGV[0].to_i)

因为这是第一次解释,我们将分别解释每一行。

Factorials(阶乘)

def fact(n)

在第一行, def 是定义一个函数的声明(或者说是一个方法; 在后面的某一章中我们将详细介绍方法)。这里,它声明了带一个参数的函数,参数是 n。

if n == 0

if用来检查一个条件。如果条件符合,下一段代码会被执行,否则 else后面的代码会被执行。

1

n为1时的值。

else

如果不为1,执行下面的代码。

n * fact(n-1)

如果条件不满足,值就是 n 乘 fact(n-1)。

end

第一个end是if条件结束。

end

第二个end是def声明的结束。

puts fact(ARGV[0].to_i)

这个调用我们的fact函数使用一个从命令行指定的值,然后打印结果。

ARGV 是一个包含命令行参数的数组。ARGV 数组的元素都是字符串,因此我们必须使用to_i把它转化成一个整数。Ruby不会像perl那样自动转化字符串成整数。

如果给这个函数传递一个负数会怎么样呢?你能看出问题吗?你能够修正这个问题吗?

字符串

下面我们将检查有关字符串中令人迷惑的问题。这里可能有点儿长,我标注了函数供参考。

01 words = ['foobar', 'baz', 'quux']
02 secret = words[rand(3)]
03
04 print "guess? "
05 while guess = STDIN.gets
06   guess.chop!
07   if guess == secret
08     puts "You win!"
09     break
10   else
11     puts "Sorry, you lose."
12   end
13   print "guess? "
14 end
15 puts "the word is ", secret, "."

在这个程序里,有个新的控制结构 while 。 在while和它对应的end之间的代码会被重复执行,直到指定的条件得到满足才退出。在这里,guess=STDIN.gets是个主动的声明 (搜集用户输入的一行字符串存储它作为程序的输入), 和一个条件(如果没有输入, guess, 它表示整个 guess=STDIN.gets 表达式的值, 如果值为 nil 循环将会推出)。

STDIN 是一个标准的输入对象。通常 guess=gets 和 guess=STDIN.gets 是一样的。

在第二行的rand(3)返回一个在0到2之间的随机数。这个随机数用来抽取数组中的一个单词。

在第5行,我们通过STDIN.gets方法从标准输入读入一行。如果 EOF (文件结束符) 在行中出现, gets返回nil。因此相关代码会重复执行直到出现 ^D (在DOS/Windows请尝试 ^Z 或者 F6), 表示输入结束。

在第六行的 guess.chop! 会去掉最后的一个字符;在这个例子中它是一个"新行"符,gets包括了反映用户的"换车"符,但是我们不感兴趣。

在15行我们输出在secret变量中的结果。我们已经写的puts (put string) 声明有两个参数,它们会被依次打印输出,但是也有使用一个参数的等效方式,把变量写成 #{secret}对于变量的计算更清晰,而不是一个可打印的单词:

puts "the word is #{secret}."

很多程序设计者感觉这样表达输出是一种很清晰的方法;它构建了一个单一的字符串和把它表达成一个单一参数传递给puts。

同样,我们现在有了使用puts作为标准的脚本输出的概念,但是这个脚本可以使用print替代,在行14和13。它们并不完全一样。 print 正确地输出给定的内容;puts也确认输出的行尾。在行14和13使用的print把光标停留在最后输出的地方,而不是移动到下一行的行首。这个为用户输入创建了一个可认识的提示。通常,下面的四个输出调用是相等的:

# 如果还没有新行,新行通过puts隐含地添加:
puts  "Darwin's wife, Esmerelda, died in a fit of penguins."

# 新行必须在print命令中明确地给出:
print "Darwin's wife, Esmerelda, died in a fit of penguins.\n"

# 你可以使用 + 连接一个新行:
print 'Darwin's wife, Esmerelda, died in a fit of penguins.'+"\n"

# 或者通过提供多于一个的字符串来连接:
print 'Darwin's wife, Esmerelda, died in a fit of penguins.', "\n"

One possible gotcha : sometimes a text window is programmed to buffer output for the sake of speed, collecting individual characters and displaying them only when it is given a newline character. So if the guessing game script misbehaves by not showing the prompt lines until after the user supplies a guess, buffering is the likely culprit. To make sure this doesn't happen, you can flush the output as soon as you have printed the prompt. It tells the standard output device (an object named STDOUT), "don't wait; display what you have in your buffer right now."

04 print "guess? "; STDOUT.flush
  ...
13 print "guess? "; STDOUT.flush

And in fact, we were more careful with this in the next script.
Regular expressions

Finally we examine this program from the chapter on regular expressions.

01 st = "\033[7m"
02 en = "\033[m"
03
04 puts "Enter an empty string at any time to exit."
05
06 while true
07   print "str> "; STDOUT.flush; str=gets.chop
08   break if str.empty?
09   print "pat> "; STDOUT.flush; pat=gets.chop
10   break if pat.empty?
11   re = Regexp.new(pat)
12   puts str.gsub(re, "#{st}\\&#{en}")
13 end

In line 6, the condition for while is hardwired to true, so it forms what looks like an infinite loop. However we put break statements in the 8th and 10th lines to escape the loop. These two breaks are also an example of "if modifiers." An if modifier executes the statement on its left hand side if and only if the specified condition is satisfied. This construction is unusual in that it operates logically from right to left, but it is provided because for many people it mimics a similar pattern in natural speech. It also has the advantage of brevity, as it needs no end statement to tell the interpreter how much of the following code is supposed to be conditional. An if modifier is conventionally used in situations where a statement and condition are short enough to fit comfortably together on one script line.

Note the difference in the user interface compared to the string-guessing script. This one lets the user quit by hitting the Return key on an empty line. We testing for emptiness of the input string, not for its nonexistence.

In lines 7 and 9 we have a "non-destructive" chop; again, we're getting rid of the unwanted newline character we always get from gets. Add the explanation point, and we have a "destructive" chop. What's the difference? In ruby, we conventionally attach '!' or '?' to the end of certain method names. The exclamation point (!, sometimes pronounced aloud as "bang!") indicates something potentially destructive, that is to say, something that can change the value of what it touches. chop! affects a string directly, but chop gives you a chopped copy without damaging the original. Here is an illustration of the difference.

ruby> s1 = "forth"
  "forth"
ruby> s1.chop!       # This changes s1.
  "fort"
ruby> s2 = s1.chop   # This puts a changed copy in s2,
  "for"
ruby> s1             # ... without disturbing s1.
  "fort"

You'll also sometimes see chomp and chomp! used. These are more selective: the end of a string gets bit off only if it happens to be a newline. So for example, "XYZ".chomp! does nothing. If you need a trick to remember the difference, think of a person or animal tasting something before deciding to take a bite, as opposed to an axe chopping indiscriminately.

The other method naming convention appears in lines 8 and 10. A question mark (?, sometimes pronounced aloud as "huh?") indicates a "predicate" method, one that can return either true or false.

Line 11 creates a regular expression object out of the string supplied by the user. The real work is finally done in line 12, which uses gsub to globally substitute each match of that expression with itself, but surrounded by ansi markups; also the same line outputs the results.

We could have broken up line 12 into separate lines like this:

highlighted = str.gsub(re,"#{st}\\&#{en}")
puts highlighted

or in "destructive" style:

str.gsub!(re,"#{st}\\&#{en}")
puts str

Look again at the last part of line 12. st and en were defined in lines 1-2 as the ANSI sequences that make text color-inverted and normal, respectively. In line 12 they are enclosed in #{} to ensure that they are actually interpreted as such (and we do not see the variable names printed instead). Between these we see \\&. This is a little tricky. Since the replacement string is in double quotes, the pair of backslashes will be interpreted as a single backslash; what gsub actually sees will be \&, and that happens to be a special code that refers to whatever matched the pattern in the first place. So the new string, when displayed, looks just like the old one, except that the parts that matched the given pattern are highlighted in inverse video.

评论[0]

Ruby的数组

09:40下午 三月 09, 2008 in category Ruby语言 by Ruby-红宝石

你可以在方括号([])内列出条目并用逗号分隔。Ruby的数组里可以容纳不同的类型对象。

ruby> ary = [1, 2, "3"]
   [1, 2, "3"]

数组可以象字符串一样连接或者重复。

ruby> ary + ["foo", "bar"]
   [1, 2, "3", "foo", "bar"]
ruby> ary * 2
   [1, 2, "3", 1, 2, "3"]

我们可以使用索引来引用数组的人一部分。

ruby> ary[0]
   1
ruby> ary[0,2]
   [1, 2]
ruby> ary[0..1]
   [1, 2]
ruby> ary[-2]
   2
ruby> ary[-2,2]
   [2, "3"]
ruby> ary[-2..-1]
   [2, "3"]

(负数表示从数组的尾部开始偏移,而不是从开头。)

数组和字符串之间可以转化,分别使用join和split:

ruby> str = ary.join(":")
   "1:2:3"
ruby> str.split(":")
   ["1", "2", "3"]
   
散列表(Hashes)
一个联合数组拥有的元素不能通过顺序的索引访问,但是可以通过键值,其可以是任何类型的值。这样的一个数组称作散列表或者字典;在Ruby里,我们使用术语“散列表(Hash)”。一个散列表可以通过在大括号({})中使用键=>值对来定义。在散列表中你使用健来查找值,就像你在数组中使用索引一样。

ruby> h = {1 => 2, "2" => "4"}
   {1=>2, "2"=>"4"}
ruby> h[1]
   2
ruby> h["2"]
   "4"
ruby> h[5]
   nil
ruby> h[5] = 10    # appending an entry
   10
ruby> h
   {5=>10, 1=>2, "2"=>"4"}
ruby> h.delete 1   # deleting an entry by key
   2
ruby> h[1]
   nil
ruby> h
   {5=>10, "2"=>"4"}
 

评论[0]

Ruby正则表达式

05:16下午 三月 08, 2008 in category Ruby语言 by Ruby-红宝石

让我们整理一下做更有趣的程序。这次我们测试一个字符串是否与描述一致,被编码成一个简明的模式。

在这些模式中有些字符和字符联合有特殊的含义,包括:

[]     范围定义 (例如, [a-z] 标志一个字符在a到z的范围中)
\w     字母或者数字; 和 [0-9A-Za-z] 相同
\W     非字母或者数字
\s     空格; 和 [ \t\n\r\f] 相同
\S     非空格字符
\d     数字字符; 和 [0-9] 相同
\D     非数字字符
\b     退格 (0x08) (仅在范围定义中)
\b     单词边界 (如果在非范围定义中)
\B     非单词边界
*     0次或者多次重复
+     至少一次或者多次重复
{m,n}     最少m次最多n次重复
?     最多重复一次; 同 {0,1}
|     或
()     组

术语“模式(pattern)”是指的正则表达式。在ruby里, 和Perl一样, 它们使用反斜杠"/"括起来而不是使用双引号。如果你以前从来没用过正则表达式, 它们虽然可以做任何事,但是你要知道你需要花费时间来熟悉它。它强大的功能会帮助你解决很多头痛的事,例如匹配、搜索等文本操作。

例如,假设我们想测试一个字符串是否符合情况: "以小写f开头,紧接着是一个大写字符,后面的数量随意,但都是非小写字符。" 如果你是一个有经验的C语言开发者,你可能已经写了很多代码在你的头脑中,是吧?包容它,你几乎不能不能帮助自己。但是在Ruby里,你尽需要使用正则表达式 /^f[A-Z][^a-z]*$/。

如何在<>中包含十六进制数字?没问题。

ruby> def chab(s)   # "contains hex in angle brackets"
    |    (s =~ /<0(x|X)(\d|[a-f]|[A-F])+>/) != nil
    | end
  nil
ruby> chab "Not this one."
  false
ruby> chab "Maybe this? {0x35}"    # wrong kind of brackets
  false
ruby> chab "Or this? <0x38z7e>"    # bogus hex digit
  false
ruby> chab "Okay, this: <0xfc0004>."
  true

虽然,乍一看,正则表达式容易让人迷惑,你将很快地喜欢上它,因为能够经济地表达自己的意图。

这里有个小程序可以帮助你联系正则表达式。把它存为regx.rb,然后通过在命令行输入"ruby regx.rb"来运行。

# Requires an ANSI terminal!

st = "\033[7m"
en = "\033[m"

puts "Enter an empty string at any time to exit."

while true
  print "str> "; STDOUT.flush; str = gets.chop
  break if str.empty?
  print "pat> "; STDOUT.flush; pat = gets.chop
  break if pat.empty?
  re = Regexp.new(pat)
  puts str.gsub(re,"#{st}\\&#{en}")
end

程序需要输入两次,一次是字符串,一次是正则表达式。字符串被用正则表达式测试,然后用屏幕的反色高亮显示匹配的部分。现在不要太关心细节,很快会有一个这个代码的分析。

str> foobar
pat> ^fo+
foobar
~~~

就像你看到的,"~~~"上字符被高亮显示。
让我们来尝试几个更多的输入。

str> abc012dbcd555
pat> \d
abc012dbcd555
   ~~~    ~~~

如果那个让你惊讶,参照本页上面的表,\d和字符d是没有关系的,而是匹配一个数字。

如果不止一种情况正确地匹配模式会怎样?

str> foozboozer
pat> f.*z
foozboozer
~~~~~~~~

foozbooz被匹配并用fooz取代,因为一个正则表达式匹配最长的可能的字字符串。

下面是一个模式来分离冒号分割的时间字段。

str> Wed Feb  7 08:58:04 JST 1996
pat> [0-9]+:[0-9]+(:[0-9]+)?
Wed Feb  7 08:58:04 JST 1996
           ~~~~~~~~

"=~" 是正则表达式的匹配操作符;它返回匹配发现的位置,如果返回nil则表示没有匹配发现。

ruby> "abcdef" =~ /d/
   3
ruby> "aaaaaa" =~ /d/
   nil

评论[0]

Ruby中的字符串

08:48上午 三月 07, 2008 in category Ruby语言 by Ruby-红宝石

Ruby处理字符串与处理数字一样。一个字符串可以使用双引号("...")或者单引号'...')括起来。
ruby> "abc"
   "abc"
ruby> 'abc'
   "abc"
在某些情况下双引号和单引号会产生不同的效果。在双引号的字符串中,可以使用反斜杠开头的脱字符,内嵌在#{}中的表达式会被求值。而在单引号中这些不会被解释,你看到的就是你得到的。例如:
ruby> puts "a\nb\nc"
a
b
c
   nil
ruby> puts 'a\nb\n'
a\nb\nc
   nil
ruby> "\n"
   "\n"
ruby> '\n'
   "\\n"
ruby> "\001"
   "\001"
ruby> '\001'
   "\\001"
ruby> "abcd #{5*3} efg"
   "abcd 15 efg"
ruby> var = " abc "
   " abc "
ruby> "1234#{var}5678"
   "1234 abc 5678"

Ruby的字符串处理更聪明,比C语言的更直观。例如,你可以使用 + 来连接字符串,重复字符串多次可以使用 * :

ruby> "foo" + "bar"
   "foobar"
ruby> "foo" * 2
   "foofoo"
在C语言中连接字符串很笨拙,因为需要直接管理内存:
char *s = malloc(strlen(s1)+strlen(s2)+1);
strcpy(s, s1);
strcat(s, s2);
/* ... */
free(s);
但是使用ruby,我们不需要考虑字符串占用的空间。我们不用去管理内存。这里是你可以使用字符串的一些操作。

连接:

ruby> word = "fo" + "o"
   "foo"

重复:

ruby> word = word * 2
   "foofoo"

抽取字符(注意,在ruby中字符用整数表示):

ruby> word[0]
   102            # 102 is ASCII code of `f'
ruby> word[-1]
   111            # 111 is ASCII code of `o'

(负数作为索引意味着偏移从字符串的尾部开始,而不是从开头开始。)

抽取子字符串:

ruby> herb = "parsley"
   "parsley"
ruby> herb[0,1]
   "p"
ruby> herb[-2,2]
   "ey"
ruby> herb[0..3]
   "pars"
ruby> herb[-5..-2]
   "rsle"

Testing for equality:

ruby> "foo" == "foo"
   true
ruby> "foo" == "bar"
   false

现在,让我们使用这些功能来做一些事情。这个难题是"猜单词," 可能单词"难题"也太有尊严了,哈哈:
# save this as guess.rb
words = ['foobar', 'baz', 'quux']
secret = words[rand(3)]

print "guess? "
while guess = STDIN.gets
  guess.chop!
  if guess == secret
    puts "You win!"
    break
  else
    puts "Sorry, you lose."
  end
  print "guess? "
end
puts "The word was ", secret, "."

现在,不用对代码的细节关注太多。下面是程序的运行情况。

% ruby guess.rb
guess? foobar
Sorry, you lose.
guess? quux
Sorry, you lose.
guess? ^D
The word was baz.

(我应该可以做的更好些,考虑到1/3的成功率。)

评论[0]

Ruby的简单例子

02:48下午 三月 05, 2008 in category Ruby语言 by Ruby-红宝石

让我们写个函数计算阶乘。数学上阶乘的定义为:

n 的阶乘:

n! = 1                (当 n==0)
   = n * (n-1)!       (否则)

在ruby里, 这个可以写为:

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

你会注意到在结尾重复的end。Ruby被称作"Algol-like"就是因为这个。(实际上ruby的语法更像Eiffel语言。)你可能注意到函数缺少一个返回声明。它是不需要的,因为ruby总是返回其最后计算的东西。在这里使用一个return声明是允许的但不是必须的。

让我们来测试这个函数,在添加一行代码来运行程序:

# Program to find the factorial of a number
# Save this as fact.rb

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

puts fact(ARGV[0].to_i)

这里, ARGV是一个包含命令行参数的数组,to_i 转换一个字符串到一个整数。

% ruby fact.rb 1
1
% ruby fact.rb 5
120

使用40做参数可以运行吗?它将会使你的计算器溢出...

% ruby fact.rb 40
815915283247897734345611269596115894272000000000

它可以运行。实际上,ruby可以处理你计算机内存允许的任意一个整数。因此 400!也可以被计算出来:

% ruby fact.rb 400
64034522846623895262347970319503005850702583026002959458684
44594280239716918683143627847864746326467629435057503585681
08482981628835174352289619886468029979373416541508381624264
61942352307046244325015114448670890662773914918117331955996
44070954967134529047702032243491121079759328079510154537266
72516278778900093497637657103263503315339653498683868313393
52024373788157786791506311858702618270169819740062983025308
59129834616227230455833952075961150530223608681043329725519
48526744322324386699484224042325998055516106359423769613992
31917134063858996537970147827206606320217379472010321356624
61380907794230459736069956759583609615871512991382228657857
95493616176544804532220078258184008484364155912294542753848
03558374518022675900061399560145595206127211192918105032491
00800000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000

看一眼并不能判断上面的结果是正确的,但是它应该是正确的,哈哈。

输入/求值 环路

当你不带参数运行ruby的时候,它从标准输入中读取命令,在输入的结尾计算它们:

% ruby
puts "hello world"
puts "good-bye world"
^D
hello world
good-bye world

上面的^D代表 Ctrl-D, 在Unix环境下结束输入的简便方法。在DOS/Windows下, 尝试用 F6 或者 ^Z 代替.

Ruby也附带了一个名为eval.rb的程序,允许从键盘交互式输入ruby代码并显示结果。我们将在这个指南的后面大量地使用它。

如果你有一个ANSI兼容的终端(如果你正在使用UNIX,基本都是ANSI兼容终端;在某些旧版本的DOS,你需要安装ANSI.SYS 或 ANSI.COM; 如果是Windows XP,很不幸,这几乎就不可能了),你应该使用这个增强的 eval.rb 来增加可视化的辅助,错误警告,和颜色加亮。另外,你可以在ruby发布里的例子子目录找到适合任何终端的非ANSI兼容的版本。下面是一个简短的eval.rb会话:

% ruby eval.rb
ruby> puts "Hello, world."
Hello, world.
   nil
ruby> exit

hello world 是 puts 生成的。下一行, 在这里是nil, 报告哪里求值结束;ruby不能够区分声明和表达式,因此求值一个代码片段和执行它是一回事。这里,nil表示puts没有返回一个有意义的值。我们可以输入exit退出解释器,虽然你也可以使用 ^D 。

贯穿这个指南,"ruby>"用来指示我们的游泳的小eval.rb程序的提示。

eval.rb内容:

#!/usr/local/bin/ruby

#######################################################
#
# Ruby interactive input/eval loop
# Written by matz (matz@netlab.co.jp)
# Modified by Mark Slagell (slagell@ruby-lang.org)
# with suggestions for improvement from Dave Thomas
# (Dave@Thomases.com)
#
#######################################################
#
# NOTE - this file has been renamed with a .txt extension to
# allow you to view or download it without the rubyist.net
# web server trying to run it as a CGI script. You will
# probably want to rename it back to eval.rb.
#
#######################################################

module EvalWrapper

# Constants for ANSI screen interaction. Adjust to your liking.
Norm = "\033[0m"
PCol = Norm # Prompt color
Code = "\033[1;32m" # yellow
Eval = "\033[0;36m" # cyan
Prompt = PCol+"ruby> "+Norm
PrMore = PCol+" | "+Norm
Ispace = " " # Adjust length of this for indentation.
Wipe = "\033[A\033[K" # Move cursor up and erase line

# Return a pair of indentation deltas. The first applies before
# the current line is printed, the second after.
def EvalWrapper.indentation( code )
case code
when /^\s*(class|module|def|if|case|while|for|begin)\b[^_]/
[0,1] # increase indentation because of keyword
when /^\s*end\b[^_]/
[-1,0] # decrease because of end
when /\{\s*(\|.*\|)?\s*$/
[0,1] # increase because of '{'
when /^\s*\}/
[-1,0] # decrease because of '}'
when /^\s*(rescue|ensure|elsif|else)\b[^_]/
[-1,1] # decrease for this line, then come back
else
[0,0] # we see no reason to change anything
end
end

# On exit, restore normal screen colors.
END { print Norm,"\n" }


##############################################################
# Execution starts here.
##############################################################

indent=0
while TRUE # Top of main loop.

# Print prompt, move cursor to tentative indentation level, and get
# a line of input from the user.
if( indent == 0 )
expr = ''; print Prompt # (expecting a fresh expression)
else
print PrMore # (appending to previous lines)
end
print Ispace * indent,Code
line = gets
print Norm

if not line
# end of input (^D) - if there is no expression, exit, else
# reset cursor to the beginning of this line.
if expr == '' then break else print "\r" end
else

# Append the input to whatever we had.
expr << line

# Determine changes in indentation, reposition this line if
# necessary, and adjust indentation for the next prompt.
begin
ind1,ind2 = indentation( line )
if( ind1 != 0 )
indent += ind1
print Wipe,PrMore,(Ispace*indent),Code,line,Norm
end
indent += ind2
rescue # On error, restart the main loop.
print Eval,"ERR: Nesting violation\n",Norm
indent = 0
redo
end

# Okay, do we have something worth evaulating?
if (indent == 0) && (expr.chop =~ /[^; \t\n\r\f]+/)
begin
result = eval(expr, TOPLEVEL_BINDING).inspect
if $! # no exception, but $! non-nil, means a warning
print Eval,$!,Norm,"\n"
$!=nil
end
print Eval," ",result,Norm,"\n"
rescue ScriptError,StandardError
$! = 'exception raised' if not $!
print Eval,"ERR: ",$!,Norm,"\n"
end
break if not line
end
end
end # Bottom of main loop
print "\n"

end




评论[0]

开始学习Ruby

10:05下午 三月 04, 2008 in category Ruby语言 by Ruby-红宝石

首先,你要看看你的机器上是否安装了Ruby。 打开一个shell控制台(此处的指示符是"%",因此不要输入%),输入

% ruby -v

(-v 选项告诉解释器打印ruby的版本),然后回车。如果安装了Ruby,你会看到类似如下的信息:

% ruby -v
ruby 1.8.3 (2005-09-21) [i586-linux]

如果Ruby没有安装,你需要请管理员安装它或者你自己安装,因为Ruby是个自由软件,安装和使用是没有限制的。

现在, 让我们来演示Ruby。你可以通过 -e 选项在命令行上直接运行一个Ruby程序:

% ruby -e 'puts "hello world"'
hello world

更传统的,一个Ruby程序可以存储在一个文件中。

% echo "puts 'hello world'" > hello.rb
% ruby hello.rb
hello world

当真正编写代码时候,你应该使用一个文本编辑器!

一些复杂并有用的事情可以在一个缩小的程序中,在一个命令行中运行。 例如,下面的程序把当前工作目录下所有C源代码文件和头文件中的 bar 用 foo 替换掉,备份原来的文件并用.bak做后缀:

% ruby -i.bak -pe 'sub "foo", "bar"' *.[ch]

这个程序的工作象 UNIX 的 cat 命令 (但是比cat运行慢些):

% ruby -pe 0 file

评论[0]

什么是Ruby程序设计语言

09:40下午 三月 04, 2008 in category Ruby语言 by Ruby-红宝石

Ruby 是 "一种为快速和简化的面向对象的解释性的脚本语言" -- 这个含义是什么呢?

解释性脚本语言:

  ● 可以被操作系统直接调用
  ● 强大的字符串操作和正则表达式
  ● 开发过程中的即时反馈

快速简单:

  ● 变量声明是不需要的
  ● 变量不需要定义
  ● 语法是简单和一致的
  ● 内存管理是自动的

面向对象程序设计:

  ● 一切都是对象
  ● 类、方法、继承等等
  ● 单态方法
  ● 通过模块“混合在一起”的函数
  ● 迭代器和关闭

同时:

  ● 多重精密整型
  ● 便捷的异常处理
  ● 动态加载
  ● 线程支持

评论[0]