Spark.lee 发表于 2009-8-20 17:06:06

通过例子学ruby

以下都是从国外网站翻译过来,自己学习的时候总结了一下,希望对大家学习ruby有所帮助。
1. Problem: “Display series of numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).”
解决方案

   1. i = 0   
   2. loop { print "#{i+=1}, " }   

   虽然是一个很简单的问题,但我想着想着却觉得这个问题很有意思,原文中也没有给出很完美的答案,不知道谁有好的解决方法。

2. Problem: “Fibonacci series, swapping two variables, finding maximum/minimum among a list of numbers.”
解决方案

   1. #Fibonacci series   
   2. Fib = Hash.new{ |h, n| n < 2 ? h = n : h = h + h }   
   3. puts Fib   
   4.   
   5. #Swapping two variables   
   6. x,y = y,x   
   7.   
   8. #Finding maximum/minimum among a list of numbers   
   9. puts .max   
10. puts .min   



语法知识:

1.Hash。Hash在实例话的时候可以在new里边接受一个参数值,或者一个模块,它实际上不是hash对象的一个值,仅当在hash操作的时候找不到这个值对应的项的时候返回。

2.交换两个变量。

3.查询数组里最大最小的值,有专门的API。

3. Problem: “Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.”

解决方案

   1. a = []   
   2. loop { break if (c = gets.chomp) == ‘q’; a << c }   
   3. p a.sort   
   4. p a.sort { |a,b| b<=>a }   



语法:

   1. loop循环,及break的应用
   2. 从键盘读入字符 gets.chomp
   3. 将一项插入到数组 a << c
   4. 对于数组的正序和倒序的排序。



4. Problem: “Reynolds number is calculated using formula (D*v*rho)/mu Where D = Diameter, V= velocity, rho = density mu = viscosity Write a program that will accept all values in appropriate units (Don’t worry about unit conversion) If number is < 2100, display Laminar flow, If it’s between 2100 and 4000 display 'Transient flow' and if more than '4000', display 'Turbulent Flow' (If, else, then...)"
ruby 代码

   1. vars = %w{D V Rho Mu}   
   2.   
   3. vars.each do |var|   
   4.   print "#{var} = "
   5.   val = gets   
   6.   eval("#{var}=#{val.chomp}")   
   7. end
   8.   
   9. reynolds = (D*V*Rho)/Mu.to_f   
10.   
11. if (reynolds < 2100)   
12.   puts "Laminar Flow"
13. elsif (reynolds > 4000)   
14.   puts "Turbulent Flow"
15. else
16.   puts "Transient Flow"
17. end

语法:

没有搞清楚vars = %w{D V Rho Mu}这一句是什么意思。

5. Problem: “Modify the above program such that it will ask for ‘Do you want to calculate again (y/n), if you say ‘y’, it’ll again ask the parameters. If ‘n’, it’ll exit. (Do while loop) While running the program give value mu = 0. See what happens. Does it give ‘DIVIDE BY ZERO’ error? Does it give ‘Segmentation fault..core dump?’. How to handle this situation. Is there something built in the language itself? (Exception Handling)”
ruby 代码

   1. vars = { "d" => nil, "v" => nil, "rho" => nil, "mu" => nil }   
   2.   
   3. begin
   4.   vars.keys.each do |var|   
   5.   print "#{var} = "
   6.   val = gets   
   7.   vars = val.chomp.to_i   
   8.   end
   9.   
10.   reynolds = (vars["d"]*vars["v"]*vars["rho"]) / vars["mu"].to_f   
11.   puts reynolds   
12.   
13.   if (reynolds < 2100)   
14.   puts "Laminar Flow"
15.   elsif (reynolds > 4000)   
16.   puts "Turbulent Flow"
17.   else
18.   puts "Transient Flow"
19.   end
20.   
21.   print "Do you want to calculate again (y/n)? "
22. end while gets.chomp != "n"   



6.一个计算器的问题,代码太多。

7. Problem: “Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places, padding zeros to the right and left, right and left justification)(Input output operations)”
ruby 代码

   1. #rounding up to 5 decimal pleaces   
   2. puts sprintf("%.5f", 124.567896)   
   3.   
   4. #truncating after 4 decimal places   
   5. def truncate(number, places)   
   6.   (number * (10 ** places)).floor / (10 ** places).to_f   
   7. end
   8.   
   9. puts truncate(124.56789, 4)   
10.   
11. #padding zeroes to the left   
12. puts ‘hello’.rjust(10,’0‘)   
13.   
14. #padding zeroes to the right   
15. puts ‘hello’.ljust(10,’0‘)   
16.   
17.   

语法:





   1. 格式化sprintf。
   2. 左填充和右填充

8. Problem: “Open a text file and convert it into HTML file. (File operations/Strings)”

这段代码比较长,其中有些东西还是不太理解,还要看看正则表达式,谁能告诉我下边的代码是怎么执行的吗:

   1. rules = {‘*something*’ => ‘something’,      
   2.          ’/something/’ => ‘something’}      
   3.      
   4. rules.each do |k,v|      
   5.   re = Regexp.escape(k).sub(/something/) {"(.+?)"}      
   6.   doc.gsub!(Regexp.new(re)) do   
   7.   content = $1   
   8.   v.sub(/something/) { content }      
   9.   end   
10. end   

9. Problem: “Time and Date : Get system time and convert it in different formats ‘DD-MON-YYYY’, ‘mm-dd-yyyy’, ‘dd/mm/yy’ etc.”
ruby 代码

   1. time = Time.now   
   2. puts time.strftime("%d-%b-%Y")   
   3. puts time.strftime("%m-%d-%Y")   
   4. puts time.strftime("%d/%m/%Y")   

10. Problem: “Create files with date and time stamp appended to the name”
ruby 代码

   1. #Create files with date and time stamp appended to the name   
   2. require 'date'   
   3.   
   4. def file_with_timestamp(name)   
   5.   t = Time.now   
   6.   open("#{name}-#{t.strftime('%m.%d')}-#{t.strftime('%H.%M')}", 'w')   
   7. end
   8.   
   9. my_file = file_with_timestamp('pp.txt')   
10. my_file.write('This is a test!')   
11. my_file.close   



11. Problem: “Input is HTML table. Remove all tags and put data in a comma/tab separated file.”

12. Problem: “Extract uppercase words from a file, extract unique words.”

   1. open('some_uppercase_words.txt').read.split().each { |word| puts word if word =~ /^+$/ }   
   2.   
   3. words = open(some_repeating_words.txt).read.split()   
   4. histogram = words.inject(Hash.new(0)) { |hash, x| hash += 1; hash}   
   5. histogram.each { |k,v| puts k if v == 1 }

语法:(对于第四行还是不太懂,谁能给我讲一下呢)

1.打开文件,读取文件,split(),正则表达式匹配。

13. Problem: “Implement word wrapping feature (Observe how word wrap works in windows ‘notepad’).”
ruby 代码

   1. input = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
   2.   
   3.   
   4. def wrap(s, len)   
   5.   result = ''
   6.   line_length = 0   
   7.   s.split.each do |word|   
   8.   if line_length + word.length + 1< len   
   9.       line_length += word.length + 1   
10.       result += (word + ' ')   
11.   else
12.       result += "\n"
13.       line_length = 0   
14.   end
15.   end
16.   result   
17. end
18.   
19. puts wrap(input, 30)   



14. Problem: “Adding/removing items in the beginning, middle and end of the array.”
ruby 代码

   1. x =    
   2.   
   3. #adding to beginning   
   4. x.unshift(0)   
   5. print x   
   6. print "\n"
   7.   
   8. #adding to the end   
   9. x << 4   
10. print x   
11. print "\n"
12. #adding to the middle   
13. x.insert(2,2)   
14. print x   
15. print "\n"
16. #removing from the beginning   
17. x.shift   
18. print x   
19. print "\n"
20. #removing from the end   
21. x.pop   
22. print x   
23. print "\n"
24. #removing from the middle   
25. x.delete(2)   
26. print x   
27. print "\n



15. Problem: “Are these features supported by your language: Operator overloading, virtual functions, references, pointers etc.”

Solution: Well this is not a real problem (not in Ruby, at least). Ruby is a very high level language ant these things are a must :) .

peterz 发表于 2009-8-21 17:35:52

不错。分量非常的足

nbkhic 发表于 2009-8-24 12:35:28

花了2个星期研究了ruby,有如下感觉,跟大家分享一下:
1.watir非常容易上手,从某种程度上说,watir比QTP都容易上手一些..
2.ruby语言对我来说非常难以学习,其中的迭代器和闭包经常让人迷失;
3.学好watir并不难,其源代码只有4000多行,各种方法也不是特别多,比较容易掌握;
4.ruby让我很迷茫,相当多的语法糖衣,比如%w{},%Q{},$,$;之类的,另外ruby中我现在都弄不明白的是include和reqire的区别...很头疼;
5.学过java的兄弟可能对于ruby的面向对象特性颇有微词,尽管说ruby中一切都是对象,但是ruby定义类的方式跟一般的面向对象语言是很不一样的...@var和@@var经常会让人烦迷糊;
6.如果仅仅是写watir脚本而不需要搭建基于watir和rails的测试框架的话,学习一点点ruby的基本语法就OK了,但是若要深入,ruby确实是一门很诡异的语言,跟C++都有得一拼...ruby中的概念非常容易混淆...当然了,可能是我天赋不够的原因...

Spark.lee 发表于 2009-8-24 14:25:19

回复 3# 的帖子

include和reqire的区别

应该还有个load

一般来说:
require 这个东西加载 只加载一次
include这个就直接放到脚本中
load一般加载会叠加 一般在程序中不使用 只是 在irb中使用

一般使用include会出现意外错误

具体的分别你可以看见:http://wiki.openqa.org/display/WTR/include+Watir

nbkhic 发表于 2009-8-24 15:25:02

确实如此,对require,include理解不深刻是因为我没有仔细理解ruby帮助文档中。
刚才又看了下,发现这两个方法作用如下:
require:加载参数文件以及引用到的类库;通过require的方法,用户可以调用所引用module中的模块级方法。示例代码如下:
module Trig
PI = 3.141592654
def Trig.sin(x)
   # ..
end
def Trig.cos(x)
   # ..
end
end

module Action
VERY_BAD = 0
BAD      = 1
def Action.sin(badness)
    # ...
end
end
###############################
require "trig"
require "action"

y = Trig.sin(Trig::PI/4)
wrongdoing = Action.sin(Action::VERY_BAD)
###################################
这时候require的调用者可以使用的是moudule方法,也就是以moudule名或self为前缀定义的方法;若是引用moudule常量的话,则需要使用“::”操作符;
##########################################无奈的分隔线##################
include则不同,其作用是糅合。将module中的非moudule方法(也就是java中的非静态方法)糅合到引用其的class中。示例代码如下:
module Debug
def whoAmI?
    "#{self.type.name} (\##{self.id}): #{self.to_s}"
end
end
class Phonograph
include Debug
# ...
end
class EightTrack
include Debug
# ...
end
ph = Phonograph.new("West End Blues")
et = EightTrack.new("Surrealistic Pillow")
#################################结果如下#####################
ph.whoAmI?&raquo; "Phonograph (#537762134): West End Blues"
et.whoAmI?&raquo; "EightTrack (#537761824): Surrealistic Pillow"
我们看帮助文档中的原话
A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include. Second, a Ruby include does not simply copy the module's instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they'll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.
也就是说inculde建立了moudule中方法的引用,引用其的类和对象就会获得module中的任何方法...
没办法,ruby不太好理解,所以我的上述说明可能会很绕....

最后再次谢谢斑竹的提示。关于require和include还有很多概念,下次专门写出来分享:)

风车 发表于 2009-9-7 12:43:58

好难。。。

buutterfly 发表于 2009-10-10 18:34:32

菜鸟学习了:D

同同爱学习 发表于 2009-11-20 11:24:29

学习了

yetties2005 发表于 2010-1-5 10:18:20

我也学习了~:victory:

sail-j 发表于 2010-4-1 16:27:55

赞一个

:victory:

dog487 发表于 2010-4-6 09:19:45

来学习了~:lol

key4 发表于 2010-5-7 21:42:11

学习呀,我最近也在看这个

e1king 发表于 2010-5-12 15:45:26

原帖由 Spark.lee 于 2009-8-20 17:06 发表 http://bbs.51testing.com/images/common/back.gif
以下都是从国外网站翻译过来,自己学习的时候总结了一下,希望对大家学习ruby有所帮助。
1. Problem: “Display series of numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit if someone h ...
vars = %w{D V Rho Mu}这一句是什么意思
TO 楼主
这句话的意思是vars={"D","V","Rho","Mu"}

SSS_51 发表于 2010-5-21 15:14:12

学到东西了,一直在思考模块化的问题

我用了最笨的load学到东西了:victory:

yang 发表于 2010-6-25 14:31:11

学习学习。。。。。。

peag 发表于 2010-7-28 09:12:28

先记着

tings 发表于 2010-9-4 14:47:45

本帖最后由 tings 于 2010-12-1 10:56 编辑

看不懂,太复杂了。








——————————————————————
my friends have recently started cheap wow gold.

swlcom 发表于 2010-9-28 09:57:40

复杂

qlyejtxy 发表于 2010-10-5 02:53:02

终于找到 了

lyscser 发表于 2010-10-10 11:23:39

Ruby在书写和可读性上太抽象了,完全不适合我这种没有逻辑头脑的人……身之不能,心向往之……
页: [1] 2
查看完整版本: 通过例子学ruby