ruby教程

合集下载

Ruby编程语言教程(Tutorials Point)说明书

Ruby编程语言教程(Tutorials Point)说明书

About the T utorialRuby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.This tutorial gives a complete understanding on Ruby.AudienceThis tutorial has been prepared for beginners to help them understand the basic to advanced concepts related to Ruby Scripting languages.PrerequisitesBefore you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs and programming languages in general.Copyright & DisclaimerCopyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our websiteorinthistutorial,******************************************iT able of ContentsAbout the Tutorial ......................................................................................................................................Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents ...................................................................................................................................... i i 1. RUBY – OVERVIEW (1)Features of Ruby (1)Tools You Will Need (2)What is Next? (2)2. RUBY – ENVIRONMENT SETUP (3)Try it Option Online (3)Local Environment Setup (3)Ruby Installation on Linux/Unix (3)Using yum to Install Ruby (4)Ruby Installation on Windows (4)Ruby Command Line Options (5)Ruby Environment Variables (7)Popular Ruby Editors (9)Interactive Ruby (IRb) (9)What is Next? (10)3. RUBY – SYNTAX (11)Whitespace in Ruby Program (11)Line Endings in Ruby Program (11)Ruby Identifiers (11)iiHere Document in Ruby (12)Ruby BEGIN Statement (13)Ruby END Statement (14)Ruby Comments (15)4. RUBY – CLASSES AND OBJECTS (16)Defining a Class in Ruby (17)Variables in a Ruby Class (17)Creating Objects in Ruby Using new Method (18)Custom Method to Create Ruby Objects (18)Member Functions in Ruby Class (19)Simple Case Study (20)5. RUBY – VARIABLES, CONSTANTS AND LITERALS (24)Ruby Global Variables (24)Ruby Instance Variables (25)Ruby Class Variables (26)Ruby Local Variables (27)Ruby Constants (27)Ruby Pseudo-Variables (28)Ruby Basic Literals (28)Integer Numbers (28)Floating Numbers (29)String Literals (29)Backslash Notations (30)Ruby Arrays (31)Ruby Hashes (31)iii6. RUBY – OPERATORS (33)Ruby Arithmetic Operators (33)Ruby Comparison Operators (33)Ruby Assignment Operators (35)Ruby Parallel Assignment (35)Ruby Bitwise Operators (36)Ruby Logical Operators (37)Ruby Ternary Operator (38)Ruby Range Operators (38)Ruby defined? Operators (38)Ruby Dot "." and Double Colon "::" Operators (40)Ruby Operators Precedence (41)7. RUBY – COMMENTS (43)Ruby Multiline Comments (43)8. RUBY –IF...ELSE, C ASE, UNLESS (45)Ruby if...else Statement . (45)Ruby if modifier (46)Ruby unless Statement (46)Ruby unless modifier (47)Ruby case Statement (47)9. RUBY – LOOPS (50)Ruby while Statement (50)Ruby while modifier (51)Ruby until Statement (51)ivRuby for Statement (53)Ruby break Statement (54)Ruby next Statement (55)Ruby redo Statement (56)Ruby retry Statement (56)10. RUBY – METHODS (58)Return Values from Methods (59)Ruby return Statement (59)Variable Number of Parameters (60)Class Methods (61)Ruby alias Statement (62)Ruby undef Statement (62)11. RUBY – BLOCKS (64)The yield Statement (64)Blocks and Methods (66)BEGIN and END Blocks (66)12. RUBY – MODULES AND MIXINS (68)Ruby require Statement (69)Ruby include Statement (70)Mixins in Ruby (71)13. RUBY – STRINGS (73)Expression Substitution (73)General Delimited Strings (73)Escape Characters (74)vString Built-in Methods (75)String unpack Directives (85)14. RUBY – ARRAYS (89)Creating Arrays (89)Array Built-in Methods (91)Array pack Directives (99)15. RUBY – HASHES (103)Creating Hashes (103)Hash Built-in Methods (104)16. RUBY – DATE AND TIME (109)Getting Current Date and Time (109)Getting Components of a Date & Time (109)Time.utc,Time.gm and Time.local Functions (110)Timezones and Daylight Savings Time (112)Formatting Times and Dates (112)Time Formatting Directives (113)Time Arithmetic (114)17. RUBY – RANGES (116)Ranges as Sequences (116)Ranges as Conditions (118)Ranges as Intervals (118)18. RUBY – ITERATORS (120)Ruby each Iterator (120)Ruby collect Iterator (121)vi19. RUBY – FILE I/O (123)The puts Statement (123)The gets Statement (123)The putc Statement (124)The print Statement (124)Opening and Closing Files (125)The File.new Method (125)The File.open Method (125)Reading and Writing Files (126)The sysread Method (126)The syswrite Method (127)The each_byte Method (127)The IO.readlines Method (128)The IO.foreach Method (128)Renaming and Deleting Files (128)File Modes and Ownership (129)File Inquiries (130)Directories in Ruby (132)Navigating Through Directories (132)Creating a Directory (132)Deleting a Directory (133)Creating Files & Temporary Directories (133)Built-in Functions (133)File Class and Methods (134)Directory Class and Methods (139)20. RUBY – EXCEPTIONS (142)viiUsing raise Statement (144)Using ensure Statement (146)Using else Statement (147)Catch and Throw (148)Class Exception (149)21. RUBY OBJECT ORIENTED (151)Ruby Class Definition (151)Define Ruby Objects (151)The initialize Method (151)The instance Variables (152)The accessor & setter Methods (152)The instance Methods (155)The class Methods and Variables (155)The to_s Method (156)Access Control (157)Class Inheritance (159)Methods Overriding (160)Operator Overloading (161)Freezing Objects (162)Class Constants (164)Create Object Using Allocate (165)Class Information (166)22. RUBY – REGULAR EXPRESSIONS (167)Regular-Expression Modifiers (167)Regular-Expression Patterns (168)viiiAnchors (173)Special Syntax with Parentheses (174)Search and Replace (174)23. RUBY – DBI (177)Architecture of a DBI Application (177)Prerequisites (178)Obtaining and Installing Ruby/DBI (178)Database Connection (179)INSERT Operation (180)Using do Statement (180)Using prepare and execute (181)READ Operation (183)Fetching the Result (184)Update Operation (190)DELETE Operation (191)Performing Transactions (192)COMMIT Operation (193)ROLLBACK Operation (193)Disconnecting Database (193)Handling Errors (194)Code Blocks with Methods (195)Driver-specific Functions and Attributes (196)24. RUBY – WEB APPLICATIONS (199)Writing CGI Scripts (199)Using cgi.rb (199)ixCreating Forms and HTML (201)Quoting Strings (203)Useful Methods in CGI Class (203)Ruby CGI (204)Cookies and Sessions (210)Ruby CGI Cookies (210)Ruby CGI Sessions (212)Web Hosting Servers (214)25. RUBY – SENDING EMAIL (215)Sending an HTML e-mail using Ruby (216)Sending Attachments as an e-mail (217)26. RUBY – SOCKET PROGRAMMING (220)What are Sockets? (220)A Simple Client (221)A Simple Server (221)Multi-Client TCP Servers (222)A Tiny Web Browser (223)Further Readings (224)27. RUBY – XML, XSLT, XPATH (225)What is XML? (225)XML Parser Architectures and APIs (225)Parsing and Creating XML using Ruby (225)DOM-like Parsing (227)SAX-like Parsing (228)XPath and Ruby (230)xFurther Reading (232)28. RUBY – WEB SERVICES (233)What is SOAP? (233)Installing SOAP4R (233)Writing SOAP4R Servers (233)Writing SOAP4R Clients (237)29. RUBY – TK GUIDE (240)Introduction (240)Installation (240)Simple Tk Application (240)Ruby/Tk Widget Classes (241)TkFrame (242)TkButton (245)TkLabel (248)TkEntry (251)TkCheckButton (256)TkRadioButton (261)TkListbox (265)TkComboBox (272)TkMenu (274)TkMenubutton (280)Tk.messageBox (284)TkScrollbar (286)TkCanvas (291)TkScale (300)xiTkToplevel (310)TkSpinbox (312)TkProgressBar (318)Dialog Box (321)Tk::Tile::Notebook (323)Tk::Tile::Paned (326)Tk::Tile::Separator (328)Ruby/Tk Font, Colors, and Images (330)Standard Configuration Options (334)Ruby/Tk Geometry Management (339)grid (339)Pack (340)Place (342)Ruby/Tk Event Handling (343)The configure Method (345)The cget Method (346)30. RUBY – LDAP (347)Ruby/LDAP Installation (347)Establish LDAP Connection (347)Adding an LDAP Entry (348)Modifying an LDAP Entry (350)Deleting an LDAP Entry (351)Modifying the Distinguished Name (352)Performing a Search (353)Handling Errors (355)xii31. RUBY – MULTITHREADING (356)Creating Ruby Threads (356)Thread Lifecycle (357)Threads and Exceptions (358)Thread Variables (358)Thread Priorities (359)Thread Exclusion (359)Handling Deadlock (361)Thread States (362)Thread Class Methods (363)Thread Instance Methods (365)32. RUBY – BUILT-IN FUNCTIONS (368)Functions for Numbers (374)Functions for Float (377)Functions for Math (378)Conversion Field Specifier (379)Test Function Arguments (381)33. RUBY – PREDEFINED VARIABLES (384)34. RUBY – PREDEFINED CONSTANTS (388)35. RUBY – ASSOCIATED TOOLS (390)Standard Ruby Tools (390)RubyGems (390)Ruby Debugger (394)Interactive Ruby (398)xiiiAdditional Ruby Tools (402)eRuby: Embeded Ruby (402)ri: Ruby Interactive Reference (403)xivRuby 1Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.You can find the name Yukihiro Matsumoto on the Ruby mailing list at . Matsumoto is also known as Matz in the Ruby community. Ruby is "A Programmer's Best Friend".Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax.Features of Ruby∙Ruby is an open-source and is freely available on the Web, but it is subject to a license. ∙Ruby is a general-purpose, interpreted programming language. ∙Ruby is a true object-oriented programming language. ∙Ruby is a server-side scripting language similar to Python and PERL. ∙Ruby can be used to write Common Gateway Interface (CGI) scripts. ∙Ruby can be embedded into Hypertext Markup Language (HTML). ∙Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily. ∙Ruby has similar syntax to that of many programming languages such as C++ and Perl. ∙Ruby is very much scalable and big programs written in Ruby are easily maintainable. ∙Ruby can be used for developing Internet and intranet applications. ∙Ruby can be installed in Windows and POSIX environments. ∙Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL. ∙Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase. ∙ Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.1. RUBY – OVERVIEWRubyT ools Y ou Will NeedFor performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software:∙Linux or Windows 95/98/2000/NT or Windows 7 operating system∙Apache 1.3.19-5 Web server∙Internet Explorer 5.0 or above Web browser∙Ruby 1.8.5This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications.What is Next?The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications.2Ruby 3Try it Option OnlineWe already have set up Ruby Programming environment online, so that you can execute almost all the tutorial examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.Try the following example using the Try it option available on our website at the top right corner of the sample code box given below:#!/usr/bin/ruby -wputs "Hello, Ruby!";For most of the examples given in this tutorial, you will find a Try it option on our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.Local Environment SetupIf you are still willing to set up your environment for Ruby programming language, then let's proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further:∙Ruby Installation on Linux/Unix : If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter. ∙Ruby Installation on Windows : If you are planning to have your development environment on Windows Machine, then go through this chapter. ∙Ruby Command Line Options : This chapter list out all the command line options, which you can use along with Ruby interpreter. ∙ Ruby Environment Variables : This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works. Ruby Installation on Linux/UnixHere are the steps to be followed to install Ruby on a Unix machine: NOTE: Before proceeding, make sure you have root privilege.∙ Download a zipped file having latest version of Ruby. Follow Download Link .2. RUBY – ENVIRONMENT SETUP∙After having downloaded the Ruby archive, unpack it and change into the newly created directory:$ tar -xvzf ruby-1.6.7.tgz$ cd ruby-1.6.7∙Now, configure and compile the source code as follows:$ ./configure$ make∙Finally, install Ruby interpreter as follows:$ su -l root # become a root user$ make install$ exit # become the original user again∙After installation, make sure everything is working fine by issuing the following command on the command-line:$ruby -vruby 1.6.7 (2002-06-04) [i386-netbsd]∙If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version.Using yum to Install RubyIf your computer is connected to the Internet, then the easiest way to install Ruby or any other other RPM is using the yum utility. Give the following command at the command prompt and you will find Ruby gets installed on your computer.$ yum install rubyRuby Installation on WindowsHere are the steps to install Ruby on a Windows machine.NOTE:You may have different versions available at the time of installation.∙Download a zipped file having latest version of Ruby. Follow Download Link.∙After having downloaded the Ruby archive, unpack it and change into the newly created directory:∙Double-click the Ruby1.6.7.exe file. The Ruby installation wizard starts.4∙Click Next to move to the Important Information page of the wizard and keep moving till Ruby installer completes installing Ruby.You may need to set some environment variables if your installation has not setup them appropriately.∙If you use Windows 9x, add the following lines to your c:\autoexec.bat: set PATH="D:\(ruby install directory)\bin;%PATH%"∙Windows NT/2000 users need to modify their registries.o Click Control Panel | System Properties | Environment Variables.o Under System Variables, select Path and click EDIT.o Add your Ruby directory to the end of the Variable Value list and click OK.o Under System Variables, select PATHEXT and click EDIT.o Add .RB and .RBW to the Variable Value list and click OK.∙After installation, make sure everything is working fine by issuing the following command on the command-line:$ruby -vruby 1.6.7∙If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version.Ruby Command Line OptionsRuby is generally run from the command line in the following way:$ ruby [ options ] [.] [ programfile ] [ arguments ... ]The interpreter can be invoked with any of the following options to control the environment and behavior of the interpreter.Option Description-a Used with -n or -p to split each line. Check -n and -p options.-c Checks syntax only, without executing program.-C dir Changes directory before executing (equivalent to -X).-d Enables debug mode (equivalent to -debug).5-F pat Specifies pat as the default separator pattern ($;) used by split.-e prog Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.-h Displays an overview of command-line options.-i [ ext] Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file isdeleted.-I dir Adds dir as the directory for loading libraries.-K [ kcode] Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF-8; and a, A, n, orN for ASCII).-l Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.-n Places code within an input loop (as in while gets; ... end).-0[ octal] Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.-p Places code within an input loop. Writes $_ for each iteration.-r lib Uses require to load lib as a library before executing.-s Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines thecorresponding variable.-T [level] Sets the level for tainting checks (1 if level not specified).-v Displays version and enables verbose mode-w Enables verbose mode. If program file not specified, reads from STDIN. -x [dir] Strips text before #!ruby line. Changes directory to dir before executing if dir is specified.-X dir Changes directory before executing (equivalent to -C).-y Enables parser debug mode.--copyright Displays copyright notice.--debug Enables debug mode (equivalent to -d).--help Displays an overview of command-line options (equivalent to -h).--version Displays version.--verbose Enables verbose mode (equivalent to -v). Sets $VERBOSE to true.--yydebug Enables parser debug mode (equivalent to -y).Single character command-line options can be combined. The following two lines express the same meaning:$ruby -ne 'print if /Ruby/' /usr/share/bin$ruby -n -e 'print if /Ruby/' /usr/share/binRuby Environment V ariablesRuby interpreter uses the following environment variables to control its behavior. The ENV object contains a list of all the current environment variables set.Variable DescriptionDLN_LIBRARY_PATH Search path for dynamically loaded modules.HOME Directory moved to when no argument is passed toDir::chdir. Also used by File::expand_path to expand "~". LOGDIR Directory moved to when no arguments are passed to7Dir::chdir and environment variable HOME isn't set.PATH Search path for executing subprocesses and searching forRuby programs with the -S option. Separate each path with acolon (semicolon in DOS and Windows).RUBYLIB Search path for libraries. Separate each path with a colon(semicolon in DOS and Windows).RUBYLIB_PREFIX Used to modify the RUBYLIB search path by replacing prefixof library path1 with path2 using the format path1;path2 orpath1path2.RUBYOPT Command-line options passed to Ruby interpreter. Ignored intaint mode (Where $SAFE is greater than 0).RUBYPATH With -S option, search path for Ruby programs. Takesprecedence over PATH. Ignored in taint mode (where $SAFEis greater than 0).RUBYSHELL Specifies shell for spawned processes. If not set, SHELL orCOMSPEC are checked.For Unix, use env command to see a list of all the environment variables.HOSTNAME=RUBYPATH=/usr/binSHELL=/bin/bashTERM=xtermHISTSIZE=1000SSH_CLIENT=122.169.131.179 1742 22SSH_TTY=/dev/pts/1USER=amroodJRE_HOME=/usr/java/jdk/jreJ2RE_HOME=/usr/java/jdk/jrePATH=/usr/local/bin:/bin:/usr/bin:/home/guest/binMAIL=/var/spool/mail/guestPWD=/home/amroodINPUTRC=/etc/inputrc8JAVA_HOME=/usr/java/jdkLANG=CHOME=/rootSHLVL=2JDK_HOME=/usr/java/jdkLOGDIR=/usr/log/rubyLOGNAME=amroodSSH_CONNECTION=122.169.131.179 1742 72.167.112.17 22LESSOPEN=|/usr/bin/lesspipe.sh %sRUBYLIB=/usr/lib/rubyG_BROKEN_FILENAMES=1_=/bin/envPopular Ruby EditorsTo write your Ruby programs, you will need an editor:∙If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus.∙VIM(Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs.∙RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.∙Ruby Development Environment(RDE)is also a very good IDE for windows users.Interactive Ruby (IRb)Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.This tool comes along with Ruby installation so you have nothing to do extra to have IRb working.Just type irb at your command prompt and an Interactive Ruby Session will start as given below:$irbirb 0.6.1(99/09/16)irb(main):001:0> def helloirb(main):002:1> out = "Hello World"irb(main):003:1> puts out9irb(main):004:1> endnilirb(main):005:0> helloHello Worldnilirb(main):006:0>Do not worry about what we did here. You will learn all these steps in subsequent chapters.What is Next?We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs.10End of ebook previewIf you liked what you saw…Buy it from our store @ https://11。

Ruby编程入门教程

Ruby编程入门教程

Ruby编程入门教程Ruby是一种简洁、灵活且具有强大功能的面向对象编程语言。

它在编程界备受瞩目,并且在各种应用程序开发中广泛使用。

本教程将带领你从零开始学习Ruby编程,掌握基本的语法和概念,并逐步引领你进入更深入的内容。

无需担心,即使你是一个完全的编程初学者,也能够轻松入门Ruby编程。

1. 准备工作在开始学习Ruby编程前,你需要确保电脑中已经安装了Ruby 解释器。

你可以从Ruby官方网站(官网网址)上下载并安装适合你操作系统的版本。

安装完成后,你可以在命令行中输入"ruby -v"来验证是否成功安装。

2. Hello, Ruby!让我们从一个经典的例子开始,编写一个简单的Ruby程序,用于输出"Hello, Ruby!"这句话。

打开任意文本编辑器,新建一个以.rb为后缀的文件,比如hello.rb。

然后将下面的代码复制进去:```rubyputs "Hello, Ruby!"```保存文件后,在命令行中执行以下命令:```bashruby hello.rb```你将看到输出了"Hello, Ruby!",恭喜你成功运行了你的第一个Ruby程序!3. 变量和数据类型在Ruby中,我们可以使用变量来存储和操作数据。

Ruby有以下几种常用的数据类型:- 整数(Integer):用于表示整数,例如:1, 2, 3。

- 浮点数(Float):用于表示带有小数点的数值,例如:3.14, 2.718。

- 字符串(String):用于表示文本数据,例如:"Hello, Ruby!"。

- 布尔值(Boolean):用于表示真或假,只有两个取值:true (真)和false(假)。

以下是一些例子,展示了如何声明和使用变量:```rubynum1 = 10num2 = 5.5name = "Ruby"is_learning = true```4. 条件语句和循环结构条件语句和循环结构是编程中非常重要的概念,它们能够帮助我们根据特定的条件执行不同的代码。

Ruby语法和基础

Ruby语法和基础
Ruby语法基础
Ruby is an Object Oriented Language
• Ruby是一门完全方面对对象旳语言, 你所操 作旳每件东西都是对象.
• Ruby中旳每件东西都具有它旳类型(class), 这些东西是这个类型(class)旳实例(instance), 所以能够这么了解: 对象(object)就是类旳实 例(class instance).
Some Basic Ruby
• 措施(method), 用关键字def来定义, 后接措 施名和参数(参数旳括号是可选旳, 但是有 ruby风格旳约定), 用end结束.
• 变量不必申明, 当我们赋值给它时, 它便存在 了.
• puts: 输出其后旳内容, 并后缀回车换行. • 字符串”…”或者’…’: 使用双引号将比使用单
• 进阶: Ruby中每件东西都是对象, 所以ruby中 旳类型也是对象.
Ruby is an Object Oriented Language
• 可觉得类定义实例变量(instance variables, 对每个实例都是唯一旳变量)和实例方法 (instance methods, 用于访问实例变量).

a = [1, ‘cat’, 3.14] a[0] # 访问第一种元素 • nil: 类似null, 表达没有任何东西旳对象.
DataStructure: Arrays and Hashes
• Ruby旳散列表和数组类似, 但使用{…}, 每个 元素需提供一种key和一种value.
• 假如访问未定义旳键值对, 将返回nil.
• lo • require: 加载指定旳文件, 只会加载一次. require “filename” • 被加载旳文件中旳局部变量不会蔓延到加

ruby安装配置详解

ruby安装配置详解

ruby安装配置详解ruby on rails推荐的生产运行环境是Linux/FreeBSD/Unix,即Unix系列的操作系统,采用lighttpd+FCGI的解决方案。

以下我将以Linux操作系统,lighttpd+FCGI,MySQL数据库为例,从源代码编译安装开始讲解。

在安装之前,应该确认Linux操作系统已经安装好gcc编译器,否则请用Linux安装光盘先行安装gcc编译器:gcc –v如能返回gcc版本号,则gcc正确安装。

下面分步骤详细讲解环境的安装和设置目录[ - ]1.安装Ruby 解析器2.安装ruby on rails3.安装ruby 的数据库适配器4.安装Ruby 的FCGI 支持5.安装lighttpd Web Server6.安装ImageMagick 和RMagic (可选)7.FAQ(疑难解答)安装Ruby 解析器一些Linux发行版本,MacOSX操作系统都自带Ruby解析器,但是我仍然建议自行下载ruby 源代码编译安装。

因为一方面可以自己定制ruby安装的路径,另一方面可以在编译过程中自行添加更多的特性。

ruby的源代码可以从Ruby官方网站下载:/en/downloads/下载源代码包到本地Linux主机,然后解压缩,进入该目录,进行配置,编译和安装:tar xzvf ruby-1.8.5.tar.gzcd ruby-1.8.5./configure –prefix=/usr/local/rubymake && make install如果想浏览所有的configure参数,可以:./configure –help |more如果不定制安装的目录,默认将安装到/usr/local目录下面。

然而我建议自行定制一个ruby的安装目录,例如/usr/local/ruby,这样便于以后的升级,不会和操作系统其他软件混在一起。

安装好以后,修改操作系统PA TH路径,加入/usr/local/ruby/bin:export PA TH=/usr/local/ruby/bin:$PATH将我们自己安装的ruby放在系统PATH前面,避免操作系统自带的ruby造成的干扰。

《Ruby on Rails敏捷开发最佳实践》PDF教程

《Ruby on Rails敏捷开发最佳实践》PDF教程

《Ruby on Rails敏捷开发最佳实践-精典章节收录》PDF教程申明:本PDF教程由网站搜集整理,如需转载,请务必注明出处。

介绍:Ruby On Rails框架一经推出,立即引起B/S结构应用开发领域革命性的变化:开发者无需理会架构,只需要按Rails框架的约定向应用中填充代码,一切OK。

为了让众多Ruby On Rails学习、工作者,以及准备使用Ruby On Rails作为开发平台的开发人员能快速掌握Ruby On Rails的开发,作者精心编写了本书,书中既详细讲解了Ruby语言的基本语法,又重点介绍了Rails框架相关知识点的各种用法。

最后给出两个综合案例,作为Ruby On Rails应用开发者的参考,读者可以通过这两个案例触类旁通,解决日常开发中的问题。

读者对象本书适用于正在使用Ruby On Rails进行应用开发的开发人员、渴望了解Ruby On Rails框架的开发人员,尤其适合有初步的Java EE开发经验,想从Java EE平台过渡到Ruby On Rails开发平台的开发者。

(未完待续)第15章Rails 的邮件抽象层本章要点·电子邮件的基础知识·SMTP 协议初步·POP3协议初步·在Ruby 程序中使用SMTP 支持发送邮件·在Ruby 程序中使用POP3支持接收邮件·ActionMailer::Base 的邮件支持·在Rails 应用中发送邮件·发送HTML 格式邮件·发送带附件的邮件·电子邮件在实际应用中的用途·账户需要激活的优势·实现注册激活系统15.4注册激活系统本章将介绍一个注册激活系统,当用户输入注册信息时,必须输入有效的邮箱,当用户注册成功后,并不能立即登录系统,而要登录注册时输入的邮箱,然后通过该邮箱内的激活邮件来激活自己账户。

ruby中的实例方法、类方法、单体方法、私有方法、protected方法

ruby中的实例方法、类方法、单体方法、私有方法、protected方法

对此略懂, 简单解答下你的问题, 这块确实是ruby深入理解的关键点.首先,要明白一点: Ruby一切皆对象.什么意思呢? Ruby一个类也是一个对象(使用XX.class知道它的类是Class),它也具备方法(即所谓的类方法). 这个可以称之谓元类(MetaClass)而Ruby中调用方法逻辑很简单:1. 查询该对象所属类中的所有方法,如果存在调用之,如果不存在则调用父类的方法.2. 如果回溯到顶级类,还不存在则调用method_missing, 默认抛出NoMethodError异常.那分析下该输出i1 = T1.newputs "i1.get_v1: #{i1.get_v1}" #输出bbb in init ##i1属于类T1的实例,调用T1的方法get_v1,得到结果.puts "T1.get_v1: #{T1.get_v1}" #输出! aaa ! ##这里调用T1的元类,即所写的self.get_v1, 得到! aaa !puts "i1.v1: #{i1.v1}" #输出bbb in init ##与第一个一致, 值得一提,attr_xx 系列方法是一个魔法,是Module中提供的方法,用在这里生成新的方法.puts "i1.get2: #{i1.get2}" #输出! @@ v2 ! ##这个类变量输出,通过实例取得类变量的值.puts "i1.get3: #{i1.get3}" #输出@@ v3 in init ##同上puts "i1.v3: #{i1.v3}" #输出这里是空的## 未赋值,当然是空的. 记住在方法中self指向类,而在类中self指向元类.所以在类中使用@var赋值,这个变量属于元类而不是你期望的类.puts "i1.vtest: #{i1.vtest}" #输出vtest ## 这个同之前的分析#puts "T1.vtest: #{T1.vtest}" 报错##元类不存在该方法,当然报错,你可以使用class <<self#attr_reader :vtest#end来打开元类的该方法,当然再赋个值,要不是空值.1、ruby中的实例方法和Java等其他语言的定义类似irb(main):065:0> class Dogirb(main):066:1> def runirb(main):067:2> puts "I'm running!"irb(main):068:2> endirb(main):069:1> end=> nilirb(main):070:0> dog = Dog.new=> #<Dog:0x7fabbbefd918 @name="Dog">irb(main):071:0> dog.runI'm running!2、类方法定义时需要在方法名前加入类名称或者self关键字irb(main):059:0> class Dogirb(main):060:1> def Dog.species #或者def self.speciesirb(main):061:2> puts "I belong to the canine"irb(main):062:2> endirb(main):063:1> end=> nilirb(main):064:0> Dog.speciesI belong to the canine注意:在ruby中类方法只能被类对象调用,不能被实例对象调用。

ruby 教程

ruby 教程

ruby 教程Ruby 是一种动态、面向对象的编程语言。

它的设计哲学之一是“程序员的幸福感”。

本教程将带你由浅入深地了解 Ruby 的基本语法和常用功能。

首先,让我们来讨论 Ruby 的变量。

在 Ruby 中,你可以直接声明变量并赋值,无需显式地标明变量的类型。

例如,你可以这样声明一个变量并赋值:```rubyname = "Ruby"```Ruby 还有一些内置的数据类型,比如字符串、数值和数组。

字符串可以使用单引号或双引号来表示。

数值可以是整数或浮点数。

数组是一个有序集合,可以存储多个元素。

```rubymessage = 'Hello, world!'count = 10prices = [9.99, 10.99, 5.99]```Ruby 还有一些常用的控制结构,比如条件语句和循环语句。

条件语句使你能够根据不同的条件执行不同的代码块。

```rubyif count > 0puts "The count is positive."elsif count < 0puts "The count is negative."elseputs "The count is zero."end```循环语句允许你重复执行一段代码。

Ruby 提供了多种循环语句的选择,比如 `while`、`for` 和 `each`。

```rubywhile count > 0puts countcount -= 1endfor i in 1..5puts iendprices.each do |price|puts priceend```除了内置的功能,Ruby 还可以使用各种类库来扩展其功能。

类库提供了许多现成的功能和工具,使你能够更快地开发程序。

这只是 Ruby 的一小部分基础知识,还有很多其他有趣的功能等待你去探索。

Ruby on Rails框架使用教程

Ruby on Rails框架使用教程

Ruby on Rails框架使用教程Ruby on Rails是一个流行的Web应用程序框架,它使用Ruby编程语言。

它易于学习和使用,提供了许多内置功能,如MVC模式、ORM等,使得开发Web应用程序变得更加容易和高效。

在本文中,我将介绍如何使用Ruby on Rails框架开发Web应用程序。

1. 安装Ruby on Rails在开始之前,你需要在你的计算机上安装Ruby on Rails。

如果你还没有安装,请先安装Ruby。

Ruby可以从官方网站https:///en/下载,并根据相关说明进行安装。

安装Ruby后,你可以使用以下命令在终端中安装Rails:```gem install rails```这个命令将从互联网下载Rails,并在本地安装。

安装完成后,你可以运行以下命令检查Rails是否成功安装:```rails -v```此命令将显示Rails的版本信息。

如果你看到了Rails的版本信息,则说明你成功安装了Rails。

2. 创建一个新的Rails应用程序接下来,你需要创建一个新的Rails应用程序。

在终端中,转到您想要创建应用程序的目录,并运行以下命令:```rails new myapp```其中`myapp`是你的应用程序的名称。

这个命令将创建一个新的Rails应用程序,并安装所有必需的依赖项。

这可能需要几分钟的时间,取决于您的Internet连接速度。

创建新应用程序后,请使用以下命令进入应用程序的目录:```cd myapp```现在你已经准备好开始开发了!3.创建和管理数据库在Rails中,您可以使用ORM(对象关系映射)来操作数据库。

Rails的默认ORM是Active Record。

它允许您使用Ruby对象来操作数据库。

在Rails的MVC模式中,Model组件处理数据库操作。

在默认情况下,Rails使用SQLite数据库。

您可以使用以下命令创建一个新的数据库:```rake db:create```这个命令将在开发环境中创建一个新的SQLite数据库。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

ruby教程
Ruby教程简介
Ruby是一种开源的、简洁而有趣的动态编程语言。

它具有极
强的可读性和表达能力,对于初学者来说非常友好。

Ruby语
言的设计理念是“简单而不失强大”,它允许开发者以一种优雅的方式表达自己的想法。

Ruby的特点之一是它的面向对象编程能力。

在Ruby中,一切都是对象,并且每个对象可以拥有自己的方法和属性。

这种特性使得Ruby能够非常方便地实现庞大的复杂系统,并能够以
模块化的方式组织代码。

Ruby的语法非常灵活,允许开发者使用各种不同的编程风格。

它支持面向对象编程、函数式编程和元编程等多种范式,使得开发者能够选择最适合自己的方式来解决问题。

Ruby还有一个非常强大的特性是它的标准库。

标准库中包含
了大量的模块和类,提供了各种各样的功能,从文件操作到网络编程,从数据库连接到图形界面等等。

这使得开发者不需要从头开始编写所有功能,而是可以直接使用标准库中提供的模块和类来加速开发过程。

此外,Ruby社区非常活跃,并且有很多优秀的第三方库和框
架可供选择。

无论是开发Web应用、科学计算还是游戏开发,都能找到适合自己的解决方案。

本教程将介绍Ruby语言的基础知识和常用的编程技巧,帮助
读者快速入门并掌握Ruby的核心概念和特性。

通过学习本教程,读者将能够编写出简洁而功能强大的Ruby程序,并能够继续深入学习和探索更高级的主题。

让我们开始学习Ruby吧!。

相关文档
最新文档