以下都是从国外网站翻译过来,自己学习的时候总结了一下,希望对大家学习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).”
解决方案
- i = 0
- loop { print "#{i+=1}, " }
虽然是一个很简单的问题,但我想着想着却觉得这个问题很有意思,原文中也没有给出很完美的答案,不知道谁有好的解决方法。
2. Problem: “Fibonacci series, swapping two variables, finding maximum/minimum among a list of numbers.”
解决方案
-
- Fib = Hash.new{ |h, n| n < 2 ? h[n] = n : h[n] = h[n - 1] + h[n - 2] }
- puts Fib[50]
-
-
- x,y = y,x
-
-
- puts [1,2,3,4,5,6].max
- puts [7,8,9,10,11].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.”
解决方案
- a = []
- loop { break if (c = gets.chomp) == ‘q’; a << c }
- p a.sort
- p a.sort { |a,b| b<=>a }
语法:
- loop循环,及break的应用
- 从键盘读入字符 gets.chomp
- 将一项插入到数组 a << c
- 对于数组的正序和倒序的排序。
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 代码
- vars = %w{D V Rho Mu}
-
- vars.each do |var|
- print "#{var} = "
- val = gets
- eval("#{var}=#{val.chomp}")
- end
-
- reynolds = (D*V*Rho)/Mu.to_f
-
- if (reynolds < 2100)
- puts "Laminar Flow"
- elsif (reynolds > 4000)
- puts "Turbulent Flow"
- else
- puts "Transient Flow"
- 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 代码
- vars = { "d" => nil, "v" => nil, "rho" => nil, "mu" => nil }
-
- begin
- vars.keys.each do |var|
- print "#{var} = "
- val = gets
- vars[var] = val.chomp.to_i
- end
-
- reynolds = (vars["d"]*vars["v"]*vars["rho"]) / vars["mu"].to_f
- puts reynolds
-
- if (reynolds < 2100)
- puts "Laminar Flow"
- elsif (reynolds > 4000)
- puts "Turbulent Flow"
- else
- puts "Transient Flow"
- end
-
- print "Do you want to calculate again (y/n)? "
- 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 代码
-
- puts sprintf("%.5f", 124.567896)
-
-
- def truncate(number, places)
- (number * (10 ** places)).floor / (10 ** places).to_f
- end
-
- puts truncate(124.56789, 4)
-
-
- puts ‘hello’.rjust(10,’0‘)
-
-
- puts ‘hello’.ljust(10,’0‘)
-
-
语法:
- 格式化sprintf。
- 左填充和右填充
8. Problem: “Open a text file and convert it into HTML file. (File operations/Strings)”
这段代码比较长,其中有些东西还是不太理解,还要看看正则表达式,谁能告诉我下边的代码是怎么执行的吗:
- rules = {‘*something*’ => ‘something’,
- ’/something/’ => ‘something’}
-
- rules.each do |k,v|
- re = Regexp.escape(k).sub(/something/) {"(.+?)"}
- doc.gsub!(Regexp.new(re)) do
- content = $1
- v.sub(/something/) { content }
- end
- 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 代码
- time = Time.now
- puts time.strftime("%d-%b-%Y")
- puts time.strftime("%m-%d-%Y")
- puts time.strftime("%d/%m/%Y")
10. Problem: “Create files with date and time stamp appended to the name”
ruby 代码
-
- require 'date'
-
- def file_with_timestamp(name)
- t = Time.now
- open("#{name}-#{t.strftime('%m.%d')}-#{t.strftime('%H.%M')}", 'w')
- end
-
- my_file = file_with_timestamp('pp.txt')
- my_file.write('This is a test!')
- 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.”
- open('some_uppercase_words.txt').read.split().each { |word| puts word if word =~ /^[A-Z]+$/ }
-
- words = open(some_repeating_words.txt).read.split()
- histogram = words.inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}
- 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 代码
- 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."
-
-
- def wrap(s, len)
- result = ''
- line_length = 0
- s.split.each do |word|
- if line_length + word.length + 1 < len
- line_length += word.length + 1
- result += (word + ' ')
- else
- result += "\n"
- line_length = 0
- end
- end
- result
- end
-
- puts wrap(input, 30)
14. Problem: “Adding/removing items in the beginning, middle and end of the array.”
ruby 代码
- x = [1,3]
-
-
- x.unshift(0)
- print x
- print "\n"
-
-
- x << 4
- print x
- print "\n"
-
- x.insert(2,2)
- print x
- print "\n"
-
- x.shift
- print x
- print "\n"
-
- x.pop
- print x
- print "\n"
-
- x.delete(2)
- print x
- 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
.
分享到:
- 2007-10-15 14:20
- 浏览 4725
- 评论(4)
- 论坛回复 / 浏览 (4 / 8481)
- 查看更多
Global site tag (gtag.js) - Google Analytics
相关推荐
Ruby是一种面向对象的、动态类型的编程语言,以其简洁、优雅的语法和强大的元编程能力而闻名。在这个"Ruby-一个Ruby的例子...通过深入学习和实践这个Ruby例子,你将更好地理解它的语法、面向对象特性和丰富的库支持。
通过以上步骤,我们不仅成功地创建了一个简单的Rails应用程序,而且还学习了如何在项目中使用MySQL数据库。这个例子对于刚接触Ruby on Rails的新手来说是非常有帮助的,它可以帮助理解整个开发流程。
在这个“ruby+selenium-webdriver测试--第一个例子源代码”中,我们将探讨如何使用Ruby和Selenium-Webdriver实现自动化测试的初步步骤。 首先,我们需要安装必要的库。确保已经安装了Ruby,并通过RubyGems来安装...
标题中的“Ruby小例子(源代码)”表明这是一个关于Ruby编程语言的学习资源,包含了多个示例源代码文件。Ruby是一种面向对象的、动态类型的编程语言,由Yukihiro Matsumoto(松本行弘)创建,它强调简洁性和可读性,...
这个"Ruby中文教程(带例子代码)"是一个非常适合初学者入门的学习资源,它以中文讲解,降低了学习门槛,同时提供了丰富的实例代码,使理论知识与实践操作相结合。 首先,我们来看“Ruby语言入门教程v1.0.pdf”。这...
Ruby Ruby简单例子 包含说明和环境配置 【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM...
在"Ruby on Rails入门例子"中,你可能会学习如何创建一个简单的Rails应用。首先,你需要安装Ruby和Rails环境,然后使用`rails new`命令生成一个新的项目。接下来,会介绍如何创建控制器、模型和视图。例如,创建一个...
只有当运行环境搭建完成后,才能找到符合以往开发习惯的 IDE 工具、看一看入门的例子、学习语言相关的知识。搭建 Ruby 运行环境是学习 Ruby 的第一步骤。 Ruby 运行环境的搭建 在 Linux 环境下,我们可以使用 apt-...
在这个例子中,我们有“rubyinstaller-1.9.1-p430.exe”文件,这是一个针对Windows的Ruby安装程序。安装过程非常直观,只需双击该exe文件,按照向导指示进行即可。在安装过程中,记得勾选添加Ruby到系统路径的选项,...
Ruby元编程是Ruby编程语言中的一个重要特色,它指的是Ruby语言允许程序员在运行时对类、方法和变量...通过阅读这本书,读者将能够找到一个有效学习Ruby元编程技术的方法,并将这些复杂的技术应用到实际的编程实践中去。
以下是一个简单的例子: ```ruby require 'graphviz' g = GraphViz.new(:G, type: :digraph) # 添加节点 node1 = g.add_nodes("node1") node2 = g.add_nodes("node2") # 添加边 g.add_edges(node1, node2) # ...
通过学习Ruby-JMeter,你不仅可以提高测试脚本的可读性和可维护性,还可以更高效地构建和维护复杂的性能测试场景。 在压缩包`ruby-jmeter-master`中,你可能会找到项目的源代码、文档、示例脚本等资源。通过查看和...
Ruby on Rails,简称RoR,是由David Heinemeier Hansson基于Ruby语言开发的一款开源Web应用程序框架,它遵循MVC(模型...学习过程中,你可以逐步理解Rails的优雅设计和强大功能,为成为一个熟练的Rails开发者奠定基础。
对于Rails开发者来说,学习Ruby不仅能帮助他们理解应用程序代码(包括Rails框架自身的代码),而且还可以更深入地开发Rails应用,熟悉Rails源代码,参与相关讨论,甚至提交bug报告和代码补丁。Ruby也为进行应用程序...
(Yukihiro "Matz" Matsumoto)在1995年创建,Ruby 语言的设计目标是让程序员的生活更愉快。...文本编辑器:选择一个文本编辑器来编写 Ruby 代码,例如 Visual Studio Code、Sublime Text 或 Atom。 Ruby 基础
文件1484234731.epub和1484234731.pdf可能包含了这本书的电子版,你可以通过它们来学习和参考。记住,实践是掌握这些概念的关键,尝试在自己的项目中应用Ruby的Map、Reduce和Select,你将更好地理解和掌握数据处理的...
《Ruby基础教程(第5版)》是一本由日本...总的来说,《Ruby基础教程(第5版)》是一本全面、易懂且充满乐趣的Ruby学习资料,无论你是编程新手还是希望深入理解Ruby的开发者,都可以通过这本书开启或深化你的Ruby之旅。