background preloader

Ruby Basic Tutorial

Ruby Basic Tutorial
Troubleshooters.Com, Code Corner and Ruby Revival Present Ruby Basic Tutorial Copyright (C) 2005 by Steve Litt Note: All materials in Ruby Revival are provided AS IS. By reading the materials in Ruby Revival you are agreeing to assume all risks involved in the use of the materials, and you are agreeing to absolve the authors, owners, and anyone else involved with Python Patrol of any responsibility for the outcome of any use of these materials, even in the case of errors and/or omissions in the materials. If you do not agree to this, you must not read these materials. To the 99.9% of you honest readers who take responsibility for your own actions, I'm truly sorry it is necessary to subject all readers to the above disclaimer. CONTENTS This is a Ruby tutorial for one not knowing Ruby. Ruby can be used as a fully object oriented language, in which case you'd create classes and objects to accomplish everything. This is the simplest possible Ruby program, hello.rb. Let's count to 10... Retry

Język programowania Ruby Module: Open3 (Ruby 2.0) Open stdin, stdout, and stderr streams and start external executable. In addition, a thread for waiting the started process is noticed. The thread has a pid method and thread variable :pid which is the pid of the started process. Block form: Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr| pid = ... exit_status = wait_thr.value } Non-block form: stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts]) pid = wait_thr[:pid] # pid of the started process. ... stdin.close # stdin, stdout and stderr should be closed explicitly in this form. stdout.close stderr.close exit_status = wait_thr.value # Process::Status object returned. The parameters cmd... is passed to Process.spawn. Open3.popen3("echo abc") {|i, o, e, t| ... } Open3.popen3("echo", "abc") {|i, o, e, t| ... } Open3.popen3(["echo", "argv0"], "abc") {|i, o, e, t| ... } If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.

Ruby in Twenty Minutes Introduction This is a small Ruby tutorial that should take no more than 20 minutes to complete. It makes the assumption that you already have Ruby installed. (If you do not have Ruby on your computer install it before you get started.) Interactive Ruby Ruby comes with a program that will show the results of any Ruby statements you feed it. Open up IRB (which stands for Interactive Ruby). If you’re using macOS open up Terminal and type irb, then hit enter. irb(main):001:0> Ok, so it’s open. Type this: "Hello World" irb(main):001:0> "Hello World" => "Hello World" Ruby Obeyed You! What just happened? irb(main):002:0> puts "Hello World" Hello World => nil puts is the basic command to print something out in Ruby. Your Free Calculator is Here Already, we have enough to use IRB as a basic calculator: irb(main):003:0> 3+2 => 5 Three plus two. irb(main):004:0> 3*2 => 6 Next, let’s try three squared: irb(main):005:0> 3**2 => 9 In Ruby ** is the way you say “to the power of”. Ok, wait, what was that last one?

Ruby in Twenty Minutes What if we want to say “Hello” a lot without getting our fingers all tired? We need to define a method! irb(main):010:0> def hi irb(main):011:1> puts "Hello World!" irb(main):012:1> end => :hi The code def hi starts the definition of the method. The Brief, Repetitive Lives of a Method Now let’s try running that method a few times: irb(main):013:0> hi Hello World! Well, that was easy. What if we want to say hello to one person, and not the whole world? irb(main):015:0> def hi(name) irb(main):016:1> puts "Hello #{name}!" So it works… but let’s take a second to see what’s going on here. Holding Spots in a String What’s the #{name} bit? irb(main):019:0> def hi(name = "World") irb(main):020:1> puts "Hello #{name.capitalize}!" A couple of other tricks to spot here. Evolving Into a Greeter What if we want a real greeter around, one that remembers your name and welcomes you and treats you always with respect. The new keyword here is class. So how do we get this Greeter class set in motion?

Ruby Constants A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant (as shown in this trivial example) - p054constwarn.rb # p054constwarn.rb A_CONST = 10 A_CONST = 20 Produces a warning: p054constwarn.rb:3: warning: already initialized constant A_CONST p054constwarn.rb:3: warning: already initialized constant A_CONST Lexically, the names of constants look like the names of local variables, except that they begin with a capital letter. Note that constants do not exist until a value is actually assigned to them. Although constants should not be changed, you can modify the internal states of the objects they reference, as seen in p055constalter.rb A_CONST = "Doshi" B_CONST = A_CONST A_CONST[0] = "J" puts A_CONST puts B_CONST Note: The program p056const.rb shows all of this: Summary

Ruby on Rails Guides 5 ways to run commands from Ruby | mentalized Every so often I have the need to execute a command line application from a Ruby application/script. And every single time I fail to remember what the different command-executing methods Ruby provides us with do. This post is primarily a brain dump to aid my failing memory, and it was triggered by an issue with my Redmine Github Hook plugin where STDERR messages were not being logged. The goal of this exercise is basically to figure out how to run a command and capture all its output – both STDOUT and STDERR – so that the output can be used in the calling script. err.rb The test script I’ll be running basically outputs two lines, one on STDOUT, the other on STDERR: #! Kernel#` (backticks) Returns the standard output of running cmd in a subshell. >> `. STDERR is output, but not captured STDOUT is captured Kernel#exec Replaces the current process by running the given external command. >> exec('. Both STDERR and STDOUT is output. Kernel#system >> system('. IO#popen >> output = IO.popen('. Open3#popen3

Ruby Tutorial with Code Samples Ruby, Ruby on Rails, and _why: The disappearance of one of the world’s most beloved computer programmers Illustration by Charlie Powell. In March 2009, Golan Levin, the director of Carnegie Mellon University’s interdisciplinary STUDIO for Creative Inquiry, invited an enigmatic and famed computer programmer known to the virtual world only as “Why the Lucky Stiff” or “_why”—no, not a typo—to speak at a CMU conference called Art && Code—also not a typo—an event where artsy nerds and nerdy artists gather to talk shop. _why came to Pittsburgh and presented his latest project to a room full of a student programmers and artists. He was scruffily handsome, seemingly in his early- to mid-30s, with shaggy brown hair falling in his eyes and a constant half-smile. At this symposium, he wore a pair of oversize sunglasses and a tidy sports coat with a red pocket square, a silly riff on a stuffy professor’s outfit. He riffed on his nom d’Internet, Why the Lucky Stiff: “Some people want to call me Mr. Back in the old days, you could hack your Commodore 64 without too much trouble. Why? That’s it.

Bitwise Magazine :: Ruby programming tutorial See also: Part One and Part Two of this series As I mentioned back in part one of this series, double-quoted strings do more work than single-quoted strings. In particular, they have the ability to evaluate bits of themselves as though they were programming code. myname = 'Fred' puts( 'Hello #{myname}' ) puts( "Hello #{myname}" ) A double-quoted string is also able to evaluate variables and attributes (‘properties’) such as, expressions such as 2*3 and bits of code such as the method-call ob.ten and ‘escape characters’ such as “\n” and “\t” representing a newline and a tab. ‘It\’s my party’ User-Defined String Delimiters If, for some reason, single and double-quotes aren’t convenient – if, for example, your strings contain lots of quote characters and you don’t want to have to keep putting backslashes in front of them – you have the option of delimiting strings in many other ways. You can even define your own string delimiters. %Q[Hello #{myname}] puts( %q+Hello #{myname}+ ) Backquotes

Ruby Z Wikibooks, biblioteki wolnych podręczników. Ruby to interpretowany, w pełni obiektowy język programowania stworzony przez Yukihiro Matsumoto (pseudonim Matz). W języku angielskim ruby oznacza rubin. Od roku 2003 lawinowo zdobywa nowych zwolenników, głównie za sprawą popularnego frameworku do tworzenia aplikacji webowych o nazwie Ruby on Rails, tworzonego przez grupę programistów pod kierownictwem Davida Heinemeiera Hanssona. W roku 2005 według statystyk sklepu Amazon dwie najpopularniejsze książki na temat Rubiego i Ruby on Rails były najlepiej sprzedawanymi pozycjami z kategorii Programowanie. Punktem wyjścia dla niniejszego podręcznika stała się książka Marka Slagella "Ruby's User Guide" udostępniona na licencji GNU Free Documentation License. Spis treści[edytuj] Podstawy[edytuj] Programowanie zorientowane obiektowo[edytuj] Licencja[edytuj] Licencja Zobacz też[edytuj] Linki zewnętrzne[edytuj]