├── .gitignore ├── Gemfile ├── README.md ├── Rakefile ├── bin └── browse ├── book.xml ├── docbook ├── examples ├── .htstatic ├── __end__.rb ├── _by-selector.rb ├── alias-for-wrapping.rb ├── ampersand-prefix-with-argument.rb ├── and-and-nil-receiver.txt ├── and-operator-fig.rb ├── anonymous-class.rb ├── aref-music.rb ├── argf-shell.txt ├── argf.rb ├── argv-shell.txt ├── argv.rb ├── array-aref-set.rb ├── array-aref.rb ├── array-assoc.rb ├── array-clear.rb ├── array-coercion.rb ├── array-combination.rb ├── array-compact-uniq.rb ├── array-concat.rb ├── array-delete-at.rb ├── array-delete-if.rb ├── array-delete.rb ├── array-fill.rb ├── array-first-last.rb ├── array-flatten.rb ├── array-index.rb ├── array-insert.rb ├── array-iteration.rb ├── array-literal-w.rb ├── array-lookup-single.rb ├── array-new.rb ├── array-order.rb ├── array-permutation-combination.rb ├── array-permutation.rb ├── array-product.rb ├── array-push-unshift.rb ├── array-rotate.rb ├── array-sample.rb ├── array-set.rb ├── array-size.rb ├── array-transpose.rb ├── asterisk-selector.rb ├── at_exit.rb ├── backticks.rb ├── bang-messages.rb ├── bare-selector-syntax.rb ├── basic-arithmetic.rb ├── basicobject-method-missing.rb ├── begin-block.rb ├── block-local-variables-example.rb ├── block-local-variables-nameerror.rb ├── block-local-variables-syntax.rb ├── break.rb ├── call-selector.rb ├── case-cf-if.rb ├── case-statement-fig.rb ├── catch-throw.rb ├── character-escape.rb ├── class-keyword-open-class.rb ├── class-keyword.rb ├── class-new-constructor.rb ├── class-singleton-class.rb ├── class-variables-inherited-top.rb ├── class-variables-inherited.rb ├── class-variables-overtaken.rb ├── class-variables-siblings.rb ├── closure-binding-nameerror.rb ├── closure-example.rb ├── closure-proc-binding.rb ├── closure-with-argument.rb ├── coding-comment.rb ├── complex-abs.rb ├── complex-arg.rb ├── complex-conj.rb ├── complex-constructor.rb ├── complex-polar.rb ├── complex-rect.rb ├── conditional-false.rb ├── conditional-true.rb ├── const-missing.rb ├── constant-reference.rb ├── control-escape.rb ├── custom-internal-iterator.rb ├── def-explicit-return-multiple.rb ├── def-implicit-return-multiple.rb ├── def-implicit-return.rb ├── def-instance-method.rb ├── def-non-ascii-name.rb ├── def-singleton-method.rb ├── define-method-class-eval.rb ├── define-method.rb ├── define-singleton-method.rb ├── defined.rb ├── dir-glob.rb ├── divmod.rb ├── double-quoted-string-literal-q.rb ├── each-selector.rb ├── each_-selector.rb ├── element-set-selector.rb ├── empty-splat.rb ├── end-block.rb ├── ensure-clause.rb ├── enu-any-all-none-one.rb ├── enu-chunk.rb ├── enu-count.rb ├── enu-cycle.rb ├── enu-detect.rb ├── enu-enumerator-instantiation.rb ├── enu-feed.rb ├── enu-find-index.rb ├── enu-first-take-drop.rb ├── enu-grep.rb ├── enu-include.rb ├── enu-inject.rb ├── enu-iterate.rb ├── enu-map.rb ├── enu-min-max-by.rb ├── enu-min-max.rb ├── enu-next.rb ├── enu-next_values.rb ├── enu-partition-group-by.rb ├── enu-select-reject.rb ├── enu-slice-before.rb ├── enu-slice-cons.rb ├── enu-sort.rb ├── enu-stopiteration.rb ├── enu-take-drop-while.rb ├── enu-zip.rb ├── enumerable-to-enum.rb ├── enumerating-subclasses.rb ├── equal-equal-selector.rb ├── equal-tilde-selector.rb ├── extend-class.rb ├── file-expand-path.rb ├── file-read.rb ├── file-realpath.rb ├── file-symlink.rb ├── float-limits.rb ├── float-roundoff.rb ├── for-loop.rb ├── gcdlcm.rb ├── global-variables.rb ├── greater-than-selector.rb ├── hash-coerce.rb ├── hash-default-value.rb ├── hash-delete.rb ├── hash-equal.rb ├── hash-identity.rb ├── hash-iteration.rb ├── hash-keys.rb ├── hash-literals.rb ├── hash-lookup.rb ├── hash-merge.rb ├── hash-rehash.rb ├── hash-size.rb ├── hash-sort.rb ├── hash-store.rb ├── hash-transform.rb ├── hash-values.rb ├── here-doc.rb ├── hex-byte-escape.rb ├── if-statement-simple.rb ├── if-statement-with-else-clause.rb ├── if-statement-with-elsif-and-else-clause.rb ├── ignoring-invalid-byte-sequence.rb ├── implicit-receiver-for-private-method.rb ├── insert-output.rb ├── integer-downto-loop.rb ├── integer-times-loop.rb ├── integer-upto-loop.rb ├── invocation-semantics-break.rb ├── invocation-semantics-return.rb ├── io-close.rb ├── io-close_on_exec.rb ├── io-close_on_exec2.rb ├── io-copy.rb ├── io-fcntl.rb ├── io-ioctl.rb ├── io-pipe.rb ├── io-select.rb ├── kernel-binding-example.rb ├── kernel-exec-1.rb ├── kernel-exec-2.rb ├── kernel-exec-3.rb ├── kernel-fork-2.rb ├── kernel-fork.rb ├── kernel-open-opts.rb ├── kernel-rand.rb ├── kernel-spawn.rb ├── kernel-system.rb ├── lambda-keyword-examples.rb ├── lambda-literal-syntax.rb ├── lazy-quantifiers.rb ├── left-shift-selector.rb ├── less-than-selector.rb ├── load.rb ├── local-variables-assignment.rb ├── local-variables-uninitialized.rb ├── local-variables.rb ├── loop-loop-fig.rb ├── math-log.rb ├── message-chaining-inconsistent-return-value.rb ├── message-chaining-return-self.rb ├── message-chaining.rb ├── message-expression-with-block.rb ├── message-expressions-omit-parentheses-syntaxerror.rb ├── meta-escape.rb ├── method-defined.rb ├── method-invocation-with-block-literal.rb ├── method-lookup.rb ├── method-receiving-block-ref.rb ├── method-using-block-argument.rb ├── method-using-block-given-yield.rb ├── method-using-block-given.rb ├── module-attr-accessor.rb ├── module-function-extend-self.rb ├── module-function-private-method.rb ├── module-function.rb ├── module-namespace-and-mixin.rb ├── module-namespacing-extend-self.rb ├── module-namespacing.rb ├── module-new.rb ├── named-arguments-with-defaults.rb ├── named-arguments-with-hash.rb ├── next.rb ├── nil-guard.rb ├── non-block-local-variables-clo.rb ├── non-block-local-variables.rb ├── not-operator-fig.rb ├── numeric-bases.rb ├── numeric-bits.rb ├── numeric-coerce.rb ├── numeric-division.rb ├── numeric-equal-coerce.rb ├── numeric-equality.rb ├── numeric-inequality.rb ├── numeric-modulo.rb ├── numeric-predicates.rb ├── numerics-rounding.rb ├── object-display.rb ├── object-methods.rb ├── object-p.rb ├── object-send-p.rb ├── object-send.rb ├── object-try.rb ├── octal-byte-escape.rb ├── optional-arguments.rb ├── or-operator-fig.rb ├── parallel-assignment-equal.rb ├── parallel-assignment-more-lvalues.rb ├── parallel-assignment-more-rvalues.rb ├── parallel-assignment-one-lvalue.rb ├── parallel-assignment-one-rvalue-nil.rb ├── parallel-assignment-one-rvalue-non-array.rb ├── parallel-assignment-one-rvalue.rb ├── parallel-assignment-rvalue-to-ary.rb ├── parallel-assignment-value.rb ├── parentheses-disambiguate-bare-identifiers.rb ├── parentheses-omitted-in-message-expressions.rb ├── pass-by-reference-dup.rb ├── pass-by-reference.rb ├── plural-selector-splat.rb ├── plus-selector.rb ├── postfix-if-statement.rb ├── postfix-rescue-statement.rb ├── postfix-unless-statement-fig.rb ├── postfix-until-statement-fig.rb ├── postfix-while-statement-fig.rb ├── precedence-associativity.rb ├── precedence-parentheses.rb ├── predicate-messages.rb ├── print-puts.rb ├── proc-calling.rb ├── proc-parameters.rb ├── putback-invalid-byte-sequence.rb ├── question-mark-suffix-non-predicate.rb ├── raise-multiple-arguments.rb ├── raise-one-argument.rb ├── ran-begin-end.rb ├── ran-equal.rb ├── ran-iterate.rb ├── ran-literal.rb ├── ran-membership.rb ├── ran-new.rb ├── random-new.rb ├── random-rand.rb ├── rational-constructor.rb ├── rational-float.rb ├── rational-numerator-denominator.rb ├── rational-rationalize.rb ├── receiver-dot-selector-syntax.rb ├── receiver-selector-arguments-syntax.rb ├── redo.rb ├── reg-possessive.rb ├── regexp-alternation.rb ├── regexp-anchors.rb ├── regexp-backreferences-lvars.rb ├── regexp-backreferences.rb ├── regexp-capturing.rb ├── regexp-classes.rb ├── regexp-group-options.rb ├── regexp-literal.rb ├── regexp-matching.rb ├── regexp-options.rb ├── regexp-quantifiers.rb ├── regexp-readability.rb ├── regexp-specify-encoding.rb ├── regexp-split.rb ├── regexp-validation.rb ├── regexps-zero-width.rb ├── remove-method.rb ├── reopened-class.rb ├── required-arguments-with-optional-arguments.rb ├── required-arguments.rb ├── rescue-clause.rb ├── respond-to-method-missing.rb ├── respond-to-private.rb ├── respond-to.rb ├── rest-arguments.rb ├── rest-parameter-with-super.rb ├── self-as-the-implicit-receiver.rb ├── send-if-respond-to.txt ├── sending-a-message.rb ├── shebang-shell.txt ├── shebang.rb ├── single-quoted-string-literal-q.rb ├── size-selector.rb ├── spaceship-selector.rb ├── splat-arguments.rb ├── splat-lvalue.rb ├── splat-rvalue.rb ├── sprintf-arguments.rb ├── sprintf-bases.rb ├── sprintf-hash.rb ├── sprintf-notation.rb ├── sprintf-textual.rb ├── sprintf-width.rb ├── stdin-stdout-stderr.rb ├── stdout-redirection.rb ├── string-case.rb ├── string-checksum.rb ├── string-comparison.rb ├── string-concat.rb ├── string-count-delete.rb ├── string-debug.rb ├── string-index.rb ├── string-numeric.rb ├── string-repetition.rb ├── string-scan.rb ├── string-split.rb ├── string-squeeze.rb ├── string-sub-gsub.rb ├── string-tr.rb ├── string-unpack-float.rb ├── string-unpack-int.rb ├── string-unpack-str.rb ├── string-upto.rb ├── string-whitespace.rb ├── struct-inheritance.rb ├── struct-new.rb ├── sub-assignment.rb ├── substring-test.rb ├── substrings.rb ├── super-module.rb ├── super.rb ├── symbol-creating.rb ├── syswrite-write-putc.rb ├── ternary-nil-receiver.txt ├── ternary-operator-on-single-line.rb ├── to_-selector.rb ├── try_convert-selector.rb ├── unboundmethod-black.rb ├── undef-method.rb ├── undefined-conversion-insert-output.rb ├── unicode-escape.rb ├── unless-statement-fig.rb ├── until-loop-fig.rb ├── visibility-specifiers-args.rb ├── visibility-specifiers.rb ├── while-loop-fig.rb ├── write-syswrite-printf.rb ├── yield-semantics-break-localjump.rb ├── yield-semantics-break.rb ├── yield-semantics-return-localjump.rb └── yield-semantics-return.rb ├── fonts ├── .htstatic ├── Barry Schwartz License.txt ├── SIL Open Font License 1.1.txt ├── eot │ ├── Inconsolata-webfont.eot │ ├── Inconsolata-webfont.eot.gz │ ├── goudy_bookletter_1911-webfont.eot │ ├── goudy_bookletter_1911-webfont.eot.gz │ ├── linlibertine_re-4.7.5-webfont.eot │ └── linlibertine_re-4.7.5-webfont.eot.gz ├── index.html ├── svg │ ├── Inconsolata-webfont.svg │ ├── Inconsolata-webfont.svg.gz │ ├── goudy_bookletter_1911-webfont.svg │ └── goudy_bookletter_1911-webfont.svg.gz ├── ttf │ ├── Inconsolata-webfont.ttf │ ├── Inconsolata-webfont.ttf.gz │ ├── OFLGoudyStM-Italic-webfont.ttf │ ├── OFLGoudyStM-Italic-webfont.ttf.gz │ ├── OFLGoudyStM-webfont.ttf │ ├── OFLGoudyStM-webfont.ttf.gz │ ├── goudy_bookletter_1911-webfont.ttf │ ├── goudy_bookletter_1911-webfont.ttf.gz │ ├── linlibertine_re-4.7.5-webfont.ttf │ └── linlibertine_re-4.7.5-webfont.ttf.gz └── woff │ ├── Inconsolata-webfont.woff │ ├── goudy_bookletter_1911-webfont.woff │ ├── linlibertine_re-4.7.5-webfont.woff │ └── linlibertine_re-4.7.5-webfont.woff.gz ├── notes └── structure ├── permalinks.yaml ├── spec ├── chapters │ ├── classes_spec.rb │ ├── closures_spec.rb │ ├── flow_spec.rb │ ├── messages_spec.rb │ ├── methods_spec.rb │ ├── modules_spec.rb │ ├── objects_spec.rb │ ├── programs_spec.rb │ ├── text_spec.rb │ └── variables_spec.rb ├── index_page_spec.rb ├── shared │ ├── any_page.rb │ ├── chapter.rb │ ├── chapter_page.rb │ ├── chapter_with_figures.rb │ ├── compression.rb │ ├── figures.rb │ ├── html_page.rb │ ├── no_compression.rb │ └── uncompressed_html.rb ├── sitemap_spec.rb ├── spec.opts └── spec_helper.rb ├── src ├── arrays.xml ├── bibliography.xml ├── classes.xml ├── closures.xml ├── concurrency.xml ├── encoding.xml ├── enumerables.xml ├── examples ├── exceptions.xml ├── figures ├── files.xml ├── flow.xml ├── globals.xml ├── glossary.xml ├── hashes.xml ├── index.xml ├── io.xml ├── keywords.xml ├── messages.xml ├── methods.xml ├── modules.xml ├── numerics.xml ├── objects.xml ├── processes.xml ├── programs.xml ├── punctuation.xml ├── ranges.xml ├── ref │ ├── array.xml │ ├── basicobject.xml │ ├── bignum.xml │ ├── binding.xml │ ├── class.xml │ ├── comparable.xml │ ├── complex.xml │ ├── dir.xml │ ├── encoding.xml │ ├── encoding_converter.xml │ ├── enumerable.xml │ ├── enumerator.xml │ ├── exception.xml │ ├── falseclass.xml │ ├── fiber.xml │ ├── file.xml │ ├── file_stat.xml │ ├── filetest.xml │ ├── fixnum.xml │ ├── float.xml │ ├── gc.xml │ ├── hash.xml │ ├── integer.xml │ ├── io.xml │ ├── kernel.xml │ ├── marshal.xml │ ├── matchdata.xml │ ├── math.xml │ ├── method.xml │ ├── module.xml │ ├── mutex.xml │ ├── nilclass.xml │ ├── numeric.xml │ ├── object.xml │ ├── objectspace.xml │ ├── proc.xml │ ├── process.xml │ ├── process_gid.xml │ ├── process_status.xml │ ├── process_sys.xml │ ├── process_uid.xml │ ├── range.xml │ ├── rational.xml │ ├── regexp.xml │ ├── signal.xml │ ├── string.xml │ ├── struct.xml │ ├── struct_tms.xml │ └── symbol.xml ├── regexps.xml ├── strings.xml ├── times.xml └── variables.xml ├── www ├── .htstatic ├── draft.png ├── examples ├── fonts ├── google18c41b892eabf75d.html ├── opensearch.xml ├── robots.txt └── small-strawberry.jpeg └── xsl ├── bibliography.xsl ├── callout.xsl ├── css.xsl ├── epigraph.xsl ├── example.xsl ├── flow.xsl ├── footnote.xsl ├── glossary.xsl ├── html5.xsl ├── index.css.xsl ├── index.xsl ├── link.xsl ├── list.xsl ├── literal.xsl ├── main.css.xsl ├── page.css.xsl ├── page.xsl ├── pdf.css.xsl ├── pdf.xsl ├── phrasing.xsl ├── preamble.xsl ├── search.xsl ├── sitemap.xsl ├── syntax.css.xsl ├── table.xsl ├── toc.css.xsl └── toc.xsl /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | *~ 3 | \#* 4 | \.\#* 5 | out/ 6 | build/ 7 | examples/*.html 8 | Gemfile.lock -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | platforms :mri_19 do 3 | gem 'nokogiri', '>=1.4.3.1' 4 | gem 'mechanize', '>=1.0.0' 5 | gem 'h5-min', '>=0.2.0' 6 | gem 'coderay', '>= 0.9.4' 7 | gem 'sinatra', '>=1.0.b' 8 | gem 'rake' 9 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Read Ruby 2 | ========= 3 | 4 | _Read Ruby_ is a book I’m writing about Ruby 1.9.2. It’s in a very rough 5 | state, but the latest version can always be viewed at 6 | [ruby.runpaint.org](http://ruby.runpaint.org/). 7 | 8 | Text and images are licensed under a [Creative 9 | Commons](http://creativecommons.org/licenses/by-nc-sa/2.0/uk/) license. 10 | Suggestions and issue reports are welcomed via the [Issue 11 | Tracker](http://github.com/runpaint/read-ruby/issues). 12 | 13 | Contributor's guide 14 | ------------------- 15 | 16 | Fork the [GitHub repository](http://github.com/runpaint/read-ruby), make 17 | commits and do pull requests. 18 | 19 | To generate the book, you'll need: 20 | 21 | * Ruby 1.9.2 (or 1.9 trunk), which can be installed via 22 | [rvm](http://rvm.beginrescueend.com/). 23 | * `xsltproc` (Available in an eponymous package on Debian and her derivatives). 24 | * The gems `coderay`, `h5-min`, `nokogiri`, `sinatra`, and `w3c_validators`. If 25 | you have the `bundler` gem installed, you can install the lot by executing 26 | `bundle install` in the repository root. 27 | * To validate the DocBook sources you'll need `xmllint` (packaged as 28 | `libxml2-utils` on Debian et al.) and/or 29 | [`oNVDL`](http://www.oxygenxml.com/onvdl.html). (Validation will be skipped 30 | if these programs aren’t installed). 31 | * `gzip` for compressing HTML/CSS/JS. Installed by default on most systems. 32 | 33 | To preview it locally: 34 | 35 | * Run `rake browse` to start the bundled web server 36 | * Navigate to `http://localhost:4567/` -------------------------------------------------------------------------------- /bin/browse: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'rubygems' 3 | require 'sinatra' 4 | require 'pathname' 5 | 6 | raise "Usage: #$0 " unless ARGV.size == 1 7 | OUT_DIR = Pathname(ARGV.first) 8 | 9 | enable :run 10 | set :public, OUT_DIR 11 | 12 | helpers do 13 | def show name 14 | glob = OUT_DIR.join(name).to_s + ?* 15 | send_file Dir[glob].sort_by(&:size).first || halt(404) 16 | end 17 | end 18 | 19 | get '/' do 20 | show 'index' 21 | end 22 | 23 | get '/*' do 24 | show params[:splat].join(?/) 25 | end 26 | -------------------------------------------------------------------------------- /docbook: -------------------------------------------------------------------------------- 1 | /usr/share/xml/docbook/ -------------------------------------------------------------------------------- /examples/.htstatic: -------------------------------------------------------------------------------- 1 | ExpiresActive on 2 | ExpiresDefault "access plus 2 months" 3 | -------------------------------------------------------------------------------- /examples/__end__.rb: -------------------------------------------------------------------------------- 1 | DATA.lines.map{|l| l.split.first} 2 | #=> ["Lovers", "part", "also", "a", "--"] 3 | __END__ 4 | Lovers for the most 5 | part are without hope: passion 6 | also is just 7 | a bridge, a means of connection 8 | -- Marina Ivanovna Tsvetaeva, "The Poem of the End" 9 | -------------------------------------------------------------------------------- /examples/_by-selector.rb: -------------------------------------------------------------------------------- 1 | (1..10).sort_by {|n| -n} 2 | #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 3 | (1..10).sort_by {|n| n % 10} 4 | #=> [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] 5 | -------------------------------------------------------------------------------- /examples/alias-for-wrapping.rb: -------------------------------------------------------------------------------- 1 | class String 2 | alias :old_to_i :to_i 3 | def to_i 4 | raise "No digits found" unless match(/\d/) 5 | old_to_i 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /examples/ampersand-prefix-with-argument.rb: -------------------------------------------------------------------------------- 1 | title = ->(name) { %w{Mr Mrs Sir Dr}.sample + ' ' + name } 2 | title.is_a?(Proc) #=> true 3 | ['Stephen Hawking', 'R. Feynman', 'Niels Bohr'].map(&title) 4 | #=> ["Dr Stephen Hawking", "Mrs R. Feynman", "Sir Niels Bohr"] 5 | -------------------------------------------------------------------------------- /examples/and-and-nil-receiver.txt: -------------------------------------------------------------------------------- 1 | receiver & & receiver.selector 2 | -------------------------------------------------------------------------------- /examples/and-operator-fig.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def power_of_2? 3 | nonzero? && (self & (self - 1)).zero? 4 | end 5 | end 6 | (0..100).select(&:power_of_2?) #=> [1, 2, 4, 8, 16, 32, 64] 7 | -------------------------------------------------------------------------------- /examples/anonymous-class.rb: -------------------------------------------------------------------------------- 1 | dog = Class.new 2 | dog.class_eval do 3 | def bark 4 | :woof 5 | end 6 | end 7 | dog.new.bark #=> :woof 8 | -------------------------------------------------------------------------------- /examples/aref-music.rb: -------------------------------------------------------------------------------- 1 | formats = %w{MP3 CD Cassette 8-Track Record} 2 | 3 | def i_buy(format) 4 | "I buy my music on #{format.downcase}" 5 | end 6 | 7 | method(:i_buy)[ formats[2] ] 8 | #=> "I buy my music on cassette" 9 | method(:i_buy)[ formats[-2..-1].join(' or ' ) ] 10 | #=> "I buy my music on 8-track or record" 11 | -------------------------------------------------------------------------------- /examples/argf-shell.txt: -------------------------------------------------------------------------------- 1 | run@paint → for l in "a" "b" "c"; do echo $l > $l; done 2 | run@paint → ruby argf.rb # Hangs; blocking on STDIN 3 | run@paint → ruby argf.rb < a 4 | [] 5 | "a\n" 6 | run@paint → ruby argf.rb a b < c 7 | ["a", "b"] 8 | "a\nb\n" 9 | run@paint → ruby argf.rb --help 10 | ["--help"] 11 | /tmp/argf.rb:4:in `read': No such file or directory - --help (Errno::ENOENT) 12 | from /tmp/argf.rb:4:in `
' 13 | -------------------------------------------------------------------------------- /examples/argf.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # argf.rb 3 | p ARGV.to_a 4 | p ARGF.read 5 | -------------------------------------------------------------------------------- /examples/argv-shell.txt: -------------------------------------------------------------------------------- 1 | run@paint → ruby -w argv.rb -n 3 "bags full" 2 | 3 3 | -n 4 | argv.rb: ["-n", "3", "bags full"] 5 | run@paint → ln -s argv.rb argv 6 | run@paint → chmod +x argv 7 | run@paint → ./argv 8 | 0 9 | nil 10 | "./argv: []" 11 | run@paint → ./argv -n 3 "bags full" 12 | 3 13 | -n 14 | ./argv: ["-n", "3", "bags full"] 15 | -------------------------------------------------------------------------------- /examples/argv.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # argv.rb 3 | puts ARGV.size 4 | puts ARGV.first 5 | puts "#$0: #{ARGV}" 6 | -------------------------------------------------------------------------------- /examples/array-aref-set.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | greek = %w{alpha beta gamma delta} 3 | greek[0] = ?α #=> "α" 4 | greek[1, 2] = [?β, ?γ] #=> ["β", "γ"] 5 | greek[-1] = ?δ #=> "δ" 6 | greek #=> ["α", "β", "γ", "δ"] 7 | -------------------------------------------------------------------------------- /examples/array-aref.rb: -------------------------------------------------------------------------------- 1 | perfect = [6, 28, 496, 8128, 33550336] 2 | perfect[0, 3] #=> [6, 28, 496] 3 | perfect[2..4] #=> [496, 8128, 33550336] 4 | perfect.values_at(-4, -2, 0) #=> [28, 8128, 6] 5 | -------------------------------------------------------------------------------- /examples/array-assoc.rb: -------------------------------------------------------------------------------- 1 | one = [[Rational(2, 3), Rational(1, 3)], 2 | [Rational(3, 5), Rational(2, 5)], 3 | [Rational(4, 7), Rational(3, 7)]] 4 | one.assoc Rational(3, 5) #=> [(3/5), (2/5)] 5 | one.rassoc Rational(2, 7) #=> [(4/7), (3/7)] 6 | one.assoc 1 #=> nil 7 | -------------------------------------------------------------------------------- /examples/array-clear.rb: -------------------------------------------------------------------------------- 1 | banned = ['Animal Farm', 'Areopagitica', 2 | 'Brave New World', 'Fanny Hill'] 3 | banned.taint 4 | banned.untrust 5 | banned.clear #=> [] 6 | banned.size #=> 0 7 | banned.tainted? #=> true 8 | banned.untrusted? #=> true 9 | -------------------------------------------------------------------------------- /examples/array-coercion.rb: -------------------------------------------------------------------------------- 1 | (10..15).to_a 2 | #=> [10, 11, 12, 13, 14, 15] 3 | {first: 1, second: 2, third: 3}.to_a 4 | #=> [[:first, 1], [:second, 2], [:third, 3]] 5 | [[:glark], 1..2, {}, :sym, ?c].select{|e| e.respond_to? :to_ary} 6 | #=> [[:glark]] 7 | Array(Complex(2, 3)) 8 | #=> [(2+3i)] 9 | Array(key: :value) 10 | #=> [[:key, :value]] 11 | Array([Math::PI, Math::E]) 12 | #=> [3.141592653589793, 2.718281828459045] 13 | -------------------------------------------------------------------------------- /examples/array-combination.rb: -------------------------------------------------------------------------------- 1 | dna = [?A, ?C, ?G, ?T] 2 | dna.combination(2).to_a 3 | #=> [["A", "C"], ["A", "G"], ["A", "T"], 4 | # ["C", "G"], ["C", "T"], ["G", "T"]] 5 | dna.repeated_combination(2).to_a 6 | #=> [["A", "A"], ["A", "C"], ["A", "G"], ["A", "T"], ["C", "C"], 7 | # ["C", "G"], ["C", "T"], ["G", "G"], ["G", "T"], ["T", "T"]] 8 | -------------------------------------------------------------------------------- /examples/array-compact-uniq.rb: -------------------------------------------------------------------------------- 1 | a = 'James Joyce'.chars.map(&:upcase!) 2 | #=> [nil, "A", "M", "E", "S", nil, nil, "O", "Y", "C", "E"] 3 | a.compact! 4 | #=> ["A", "M", "E", "S", "O", "Y", "C", "E"] 5 | a.uniq 6 | #=> ["A", "M", "E", "S", "O", "Y", "C"] 7 | a.compact! 8 | #=> nil 9 | -------------------------------------------------------------------------------- /examples/array-concat.rb: -------------------------------------------------------------------------------- 1 | parents = %w{Michael Susan} 2 | grandparents = %w{Thomas Isobel} 3 | $, = ?\ 4 | (parents + grandparents).join #=> "Michael Susan Thomas Isobel" 5 | parents * ', ' #=> "Michael, Susan" 6 | parents * 2 7 | #=> ["Michael", "Susan", "Michael", "Susan"] 8 | -------------------------------------------------------------------------------- /examples/array-delete-at.rb: -------------------------------------------------------------------------------- 1 | at = Array.instance_methods(false).grep(/at$/) 2 | #=> [:at, :concat, :values_at, :delete_at] 3 | at.delete_at 1 #=> :concat 4 | at.shift #=> :at 5 | at.pop #=> :delete_at 6 | at #=> [:values_at] 7 | -------------------------------------------------------------------------------- /examples/array-delete-if.rb: -------------------------------------------------------------------------------- 1 | digits = (0..9).to_a 2 | digits.delete_if{|d| d > 7} 3 | #=> [0, 1, 2, 3, 4, 5, 6, 7] 4 | digits.keep_if(&:odd?) 5 | #=> [1, 3, 5, 7] 6 | digits.select!{|d| d**2 > d} 7 | #=> [3, 5, 7] 8 | digits.reject!(&:even?) 9 | #=> nil 10 | -------------------------------------------------------------------------------- /examples/array-delete.rb: -------------------------------------------------------------------------------- 1 | italians = %w{Abbati Albertinelli Allori Allori Altichiero 2 | Amigoni Angelico Anguissola Arcimboldo} 3 | italians.delete('Allori') #=> "Allori" 4 | italians.delete('Abbati') #=> "Abbati" 5 | italians.delete('Allori') #=> nil 6 | italians.delete('Azzolini') do |name| 7 | "#{name}: ???" 8 | end #=> "Azzolini: ???" 9 | italians 10 | #=> ["Albertinelli", "Altichiero", "Amigoni", 11 | # "Angelico", "Anguissola", "Arcimboldo"] 12 | -------------------------------------------------------------------------------- /examples/array-fill.rb: -------------------------------------------------------------------------------- 1 | notes = Array.new(7) 2 | notes.fill ?F 3 | #=> ["F", "F", "F", "F", "F", "F", "F"] 4 | notes.fill ?B, 6 5 | #=> ["F", "F", "F", "F", "F", "F", "B"] 6 | notes.fill ?A, 5, 1 7 | #=> ["F", "F", "F", "F", "F", "A", "B"] 8 | notes.fill ?G, 4...5 9 | #=> ["F", "F", "F", "F", "G", "A", "B"] 10 | notes.fill(0..2) do |i| 11 | case i 12 | when 0 then ?C 13 | when 1 then ?D 14 | when 2 then ?E 15 | end 16 | end #=> ["C", "D", "E", "F", "G", "A", "B"] 17 | -------------------------------------------------------------------------------- /examples/array-first-last.rb: -------------------------------------------------------------------------------- 1 | alpha = [*(?a..?z)] 2 | (alpha.first..alpha.last).to_a[0] #=> "a" 3 | alpha.last 3 #=> ["x", "y", "z"] 4 | -------------------------------------------------------------------------------- /examples/array-flatten.rb: -------------------------------------------------------------------------------- 1 | pow = [[1, [1, [1]]], 2 | [2, [4, [8]]], 3 | [3, [9, [27]]], 4 | [4, [16, [64]]]] 5 | pow.flatten 6 | #=> [1, 1, 1, 2, 4, 8, 3, 9, 27, 4, 16, 64] 7 | pow.flatten(1) 8 | #=> [1, [1, [1]], 2, [4, [8]], 3, [9, [27]], 4, [16, [64]]] 9 | -------------------------------------------------------------------------------- /examples/array-index.rb: -------------------------------------------------------------------------------- 1 | ruler = [*'Ramesses II'.chars] 2 | ruler.index('e') #=> 3 3 | ruler.rindex('e') #=> 6 4 | ruler.index {|e| e =~ /[[:upper:]]/} #=> 0 5 | -------------------------------------------------------------------------------- /examples/array-insert.rb: -------------------------------------------------------------------------------- 1 | a = [] 2 | a.insert 0, 0 #=> [0] 3 | a.insert -1, 1, 2, 3 #=> [0, 1, 2, 3] 4 | a.insert 0, -1 #=> [-1, 0, 1, 2, 3] 5 | -------------------------------------------------------------------------------- /examples/array-iteration.rb: -------------------------------------------------------------------------------- 1 | drops = [165, 168, 173, 180] 2 | weight = 14.0 3 | drops.each do |cm| 4 | puts "Use a #{cm} cm rope for a man of #{weight} stone" 5 | weight -= 0.5 6 | end 7 | # Use a 165 cm rope for a man of 14.0 stone 8 | # Use a 168 cm rope for a man of 13.5 stone 9 | # Use a 173 cm rope for a man of 13.0 stone 10 | # Use a 180 cm rope for a man of 12.5 stone 11 | drops.each_with_index.to_a 12 | #=> [[165, 0], [168, 1], [173, 2], [180, 3]] 13 | -------------------------------------------------------------------------------- /examples/array-literal-w.rb: -------------------------------------------------------------------------------- 1 | colours = %w{red green blue} #=> ["red", "green", "blue"] 2 | %W{Kind of #{colours.last.capitalize}} #=> ["Kind", "of", "Blue"] 3 | -------------------------------------------------------------------------------- /examples/array-lookup-single.rb: -------------------------------------------------------------------------------- 1 | colours = %w{red green blue} 2 | "#{colours[0]}, #{colours.at(1)}, and #{colours.slice(-1)}" 3 | #=> "red, green, and blue" 4 | colours[4] #=> nil 5 | colours.fetch(-5, 'white') #=> "white" 6 | colours.fetch(4) 7 | #=> index 4 outside of array bounds: -3...3 (IndexError) 8 | -------------------------------------------------------------------------------- /examples/array-new.rb: -------------------------------------------------------------------------------- 1 | Array.new #=> [] 2 | Array.new 3 #=> [nil, nil, nil] 3 | Array.new 5, :default 4 | #=> [:default, :default, :default, :default, :default] 5 | Array.new [42] #=> [42] 6 | Array.new(10){|i| i**i} 7 | #=> [1, 1, 4, 27, 256, 3125, 46656, 8 | # 823543, 16777216, 387420489] 9 | -------------------------------------------------------------------------------- /examples/array-order.rb: -------------------------------------------------------------------------------- 1 | words = %w{zero one two three four five} 2 | words.sort! 3 | #=> ["five", "four", "one", "three", "two", "zero"] 4 | words.reverse 5 | #=> ["zero", "two", "three", "one", "four", "five"] 6 | words.shuffle 7 | #=> ["two", "three", "five", "one", "four", "zero"] 8 | -------------------------------------------------------------------------------- /examples/array-permutation-combination.rb: -------------------------------------------------------------------------------- 1 | dna = [?A, ?C, ?G, ?T] 2 | dna.permutation(2).to_a 3 | #=> [["A", "C"], ["A", "G"], ["A", "T"], ["C", "A"], ["C", "G"], 4 | # ["C", "T"], ["G", "A"], ["G", "C"], ["G", "T"], ["T", "A"], 5 | # ["T", "C"], ["T", "G"]] 6 | dna.combination(2).to_a 7 | #=> [["A", "C"], ["A", "G"], ["A", "T"], 8 | # ["C", "G"], ["C", "T"], ["G", "T"]] 9 | -------------------------------------------------------------------------------- /examples/array-permutation.rb: -------------------------------------------------------------------------------- 1 | dna = [?A, ?C, ?G, ?T] 2 | dna.permutation(2).to_a 3 | #=> [["A", "C"], ["A", "G"], ["A", "T"], ["C", "A"], ["C", "G"], 4 | # ["C", "T"], ["G", "A"], ["G", "C"], ["G", "T"], ["T", "A"], 5 | # ["T", "C"], ["T", "G"]] 6 | dna.repeated_permutation(2).select{|a,b| a == b} 7 | #=> [["A", "A"], ["C", "C"], ["G", "G"], ["T", "T"]] 8 | -------------------------------------------------------------------------------- /examples/array-product.rb: -------------------------------------------------------------------------------- 1 | one_two = [1, 2] 2 | ab = [?a, ?b] 3 | one_two.product(ab, [:_]) 4 | #=> [[1, "a", :_], [1, "b", :_], [2, "a", :_], [2, "b", :_]] 5 | -------------------------------------------------------------------------------- /examples/array-push-unshift.rb: -------------------------------------------------------------------------------- 1 | kubrick = [] 2 | kubrick << 'Lolita' #=> ["Lolita"] 3 | kubrick.push('Dr. Strangelove', 4 | '2001', 5 | 'A Clockwork Orange') 6 | #=> ["Lolita", "Dr. Strangelove", "2001", "A Clockwork Orange"] 7 | kubrick.unshift 'Spartacus' 8 | #=> ["Spartacus", "Lolita", "Dr. Strangelove", "2001", "A Clockwork Orange"] 9 | -------------------------------------------------------------------------------- /examples/array-rotate.rb: -------------------------------------------------------------------------------- 1 | alpha = [*(?a..?z)] 2 | rot13 = 'Read Ruby 1.9'.chars.map do |c| 3 | if alpha.include?(d = c.downcase) 4 | alpha.rotate! until alpha.first == d 5 | d = alpha.rotate(13).first 6 | c.downcase! ? d.upcase : d 7 | else 8 | c 9 | end 10 | end.join 11 | rot13 #=> "Ernq Ehol 1.9" 12 | -------------------------------------------------------------------------------- /examples/array-sample.rb: -------------------------------------------------------------------------------- 1 | fractions = [Rational(1, 3), Rational(1, 2), Rational(4, 5)] 2 | fractions.sample #=> (1/2) 3 | fractions.sample 5 #=> [(4/5), (1/2), (1/3)] 4 | -------------------------------------------------------------------------------- /examples/array-set.rb: -------------------------------------------------------------------------------- 1 | male_names = %w{Alex Brian Chris Dave} 2 | female_names = %w{Alex Bernice Chris Denise} 3 | male_names - female_names 4 | #=> ["Brian", "Dave"] 5 | male_names & female_names 6 | #=> ["Alex", "Chris"] 7 | male_names | female_names 8 | #=> ["Alex", "Brian", "Chris", "Dave", "Bernice", "Denise"] 9 | -------------------------------------------------------------------------------- /examples/array-size.rb: -------------------------------------------------------------------------------- 1 | ascii = (0..127).map(&:chr) 2 | ascii.size #=> 128 3 | ascii *= 2 4 | ascii.size #=> 256 5 | ascii.clear.empty? #=> true 6 | -------------------------------------------------------------------------------- /examples/array-transpose.rb: -------------------------------------------------------------------------------- 1 | prime_fact = [[1, 1], [2, 1], [3, 1], [4, 2], 2 | [5, 1], [6, 2], [7, 1], [8, 3], [9, 2]] 3 | prime_fact.transpose 4 | #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9], 5 | # [1, 1, 1, 2, 1, 2, 1, 3, 2]] 6 | prime_fact.transpose.transpose == prime_fact 7 | #=> true 8 | -------------------------------------------------------------------------------- /examples/asterisk-selector.rb: -------------------------------------------------------------------------------- 1 | 45 * 2 #=> 90 2 | '45' * 2 #=> "4545" 3 | [45] * 2 #=> [45, 45] 4 | -------------------------------------------------------------------------------- /examples/at_exit.rb: -------------------------------------------------------------------------------- 1 | at_exit { puts 1 } 2 | puts 2 3 | at_exit { puts 3 } 4 | at_exit { puts 4 } if false 5 | # Output: 6 | # 2 7 | # 3 8 | # 1 9 | -------------------------------------------------------------------------------- /examples/backticks.rb: -------------------------------------------------------------------------------- 1 | `date` #=> "Tue Feb 16 04:01:10 GMT 2010\n" 2 | file = '/etc/fstab' 3 | %x.chomp 4 | #=> "-rw-r--r-- 1 root root 753 2009-11-19 13:36 /etc/fstab" 5 | -------------------------------------------------------------------------------- /examples/bang-messages.rb: -------------------------------------------------------------------------------- 1 | dungeon = 'oubliette' 2 | dungeon.capitalize #=> "Oubliette" 3 | dungeon #=> "oubliette" 4 | dungeon.capitalize! #=> "Oubliette" 5 | dungeon #=> "Oubliette" 6 | -------------------------------------------------------------------------------- /examples/bare-selector-syntax.rb: -------------------------------------------------------------------------------- 1 | def hop 2 | :boing! 3 | end 4 | hop #=> :boing! 5 | hop = :skip 6 | hop #=> :skip 7 | jump = :leap 8 | jump #=> :leap 9 | -------------------------------------------------------------------------------- /examples/basic-arithmetic.rb: -------------------------------------------------------------------------------- 1 | 1 + 2 #=> 3 2 | 34.5 - 30 #=> 4.5 3 | Rational(5,6) * 0.5 #=> 0.4166666666666667 4 | 80 / 5 #=> 16 5 | (1 + ((3.0 - 1) * 2)) * 7 #=> 35.0 6 | Complex(Rational(3, 4), 3) + Complex(4, 5) #=> ((19/4)+8i) 7 | -------------------------------------------------------------------------------- /examples/basicobject-method-missing.rb: -------------------------------------------------------------------------------- 1 | class BasicObject 2 | public :method_missing 3 | end 4 | b = BasicObject.new 5 | b.method_missing :glark 6 | #=> NoMethodError: undefined method `glark' for # 7 | -------------------------------------------------------------------------------- /examples/begin-block.rb: -------------------------------------------------------------------------------- 1 | puts 1 2 | BEGIN { puts 2 } 3 | puts 3 4 | # Output: 5 | # 2 6 | # 1 7 | # 3 8 | -------------------------------------------------------------------------------- /examples/block-local-variables-example.rb: -------------------------------------------------------------------------------- 1 | v = :out 2 | 1.times do |;v,w| # Define `v` and `w` block-local 3 | v, w = :in, :in 4 | p [v, w] 5 | end #=> [:in, :in] 6 | # `v` preserves its value from before the block 7 | v #=> :out 8 | # `w` wasn’t defined outside the block, so it still isn’t 9 | w #=> NameError: undefined local variable or method `w' for main:Object 10 | -------------------------------------------------------------------------------- /examples/block-local-variables-nameerror.rb: -------------------------------------------------------------------------------- 1 | v = :out 2 | 1.times do |;v,w| # Define `v` and `w` block-local 3 | v, w = :in, :in 4 | p [v, w] 5 | end #=> [:in, :in] 6 | # `v` preserves its value from before the block 7 | v #=> :out 8 | # `w` wasn’t defined outside the block, so it still isn’t 9 | w #=> NameError: undefined local variable or method `w' for main:Object 10 | -------------------------------------------------------------------------------- /examples/block-local-variables-syntax.rb: -------------------------------------------------------------------------------- 1 | # `a` and `b` are normal parameters; `c` and `d` are block-local 2 | Proc.new { |a, b=3.14;c, d| } 3 | ->(a, b=3.14;c, d){ } 4 | -------------------------------------------------------------------------------- /examples/break.rb: -------------------------------------------------------------------------------- 1 | (1..20).map{|i| i.to_s(2)}.each do |binary| 2 | break binary if binary.size > 4 && binary[-1] == '1' 3 | end #=> "10001" 4 | -------------------------------------------------------------------------------- /examples/call-selector.rb: -------------------------------------------------------------------------------- 1 | class Girl 2 | def initialize(name) 3 | @name = name.capitalize 4 | end 5 | 6 | def call(*sweet_nothings) 7 | "#@name: #{sweet_nothings.sample}..." 8 | end 9 | end 10 | 11 | jessica = Girl.new :jessica 12 | jessica.call('Your eyes are a blue million miles', 13 | 'For all eternity') 14 | #=> "Jessica: Your eyes are a blue million miles..." 15 | rose = Girl.new :rose 16 | rose.('I would walk 10, 000 miles', 17 | 'Superlatives cannot express') 18 | #=> "Rose: Superlatives cannot express..." 19 | -------------------------------------------------------------------------------- /examples/case-cf-if.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def ordinal 3 | if to_s =~ /^1\d$/ then 'th' 4 | elsif to_s =~ /1$/ then 'st' 5 | elsif to_s =~ /2$/ then 'nd' 6 | elsif to_s =~ /3$/ then 'rd' 7 | else 'th' 8 | end 9 | end 10 | end 11 | [1,2,3,4].map{|n| "#{n}#{n.ordinal}"} #=> ["1st", "2nd", "3rd", "4th"] 12 | 13 | class Integer 14 | def ordinal 15 | case to_s 16 | when /^1\d$/ then 'th' 17 | when /1$/ then 'st' 18 | when /2$/ then 'nd' 19 | when /3$/ then 'rd' 20 | else 'th' 21 | end 22 | end 23 | end 24 | [1,2,3,4].map{|n| "#{n}#{n.ordinal}"} #=> ["1st", "2nd", "3rd", "4th"] 25 | -------------------------------------------------------------------------------- /examples/case-statement-fig.rb: -------------------------------------------------------------------------------- 1 | MAX_REDIRECTS = 5 2 | redirects = 0 3 | [200, 404, 408, 302, 500].map do |status_code| 4 | case status_code 5 | when 408, 504 then :timeout 6 | when 100...200 then :informational 7 | when 200...300 then :success 8 | when 300...400 9 | (redirects += 1) < MAX_REDIRECTS ? :redirection 10 | : (raise "Redirection limit exceeded") 11 | when 400...500 then :client_error 12 | when 500...600 then :server_error 13 | else raise "Invalid status code: #{status_code}" 14 | end 15 | end #=> [:success, :client_error, :timeout, :redirection, :server_error] 16 | -------------------------------------------------------------------------------- /examples/catch-throw.rb: -------------------------------------------------------------------------------- 1 | require 'net/http' 2 | 3 | def follow(url) 4 | chain = [] 5 | while url do 6 | url = catch(:redirect) do 7 | chain << url = URI.parse(url) 8 | resp = Net::HTTP.new(url.host).get url.path 9 | case resp.code.to_i 10 | when 200 then return chain.join(' => ') 11 | when 300...400 then throw :redirect, resp['location'] 12 | else raise "#{url} => #{resp.code}: #{resp.message}" 13 | end 14 | end 15 | end 16 | end 17 | follow('http://w3c.org/html') 18 | #=> "http://w3c.org/html => http://www.w3.org/html => http://www.w3.org/html/" 19 | -------------------------------------------------------------------------------- /examples/character-escape.rb: -------------------------------------------------------------------------------- 1 | puts "The worst\b\b\b\b\b\b best " #=> "The best " 2 | puts "s p\sa\tc\ve\ s" 3 | #=> s p a c 4 | #=> e s 5 | puts "no\ 6 | space" #=> 'nospace' 7 | -------------------------------------------------------------------------------- /examples/class-keyword-open-class.rb: -------------------------------------------------------------------------------- 1 | class Dog 2 | end 3 | -------------------------------------------------------------------------------- /examples/class-keyword.rb: -------------------------------------------------------------------------------- 1 | class Dog 2 | end 3 | -------------------------------------------------------------------------------- /examples/class-new-constructor.rb: -------------------------------------------------------------------------------- 1 | Dog = Class.new 2 | -------------------------------------------------------------------------------- /examples/class-singleton-class.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | class P 3 | def self.convoluted? 4 | true 5 | end 6 | end 7 | C = Class.new(P) 8 | C.superclass == P #=> true 9 | C.singleton_class.superclass == P.singleton_class #=> true 10 | C.convoluted? #=> true 11 | -------------------------------------------------------------------------------- /examples/class-variables-inherited-top.rb: -------------------------------------------------------------------------------- 1 | @@cvar = :top 2 | class Top 3 | def self.cvar 4 | @@cvar 5 | end 6 | end 7 | Top.cvar #=> :top 8 | class Top 9 | @@cvar = :class 10 | end 11 | Top.cvar #=> :class 12 | @@cvar #=> :class 13 | -------------------------------------------------------------------------------- /examples/class-variables-inherited.rb: -------------------------------------------------------------------------------- 1 | class Parent 2 | @@cvar = :parent 3 | def self.cvar 4 | @@cvar 5 | end 6 | end 7 | Child = Class.new Parent 8 | Parent.cvar #=> :parent 9 | Child.cvar #=> :parent 10 | -------------------------------------------------------------------------------- /examples/class-variables-overtaken.rb: -------------------------------------------------------------------------------- 1 | class Top 2 | @@cvar = :class 3 | def self.cvar 4 | @@cvar 5 | end 6 | end 7 | @@cvar = :top 8 | Top.cvar #=> :top 9 | # warning: class variable @@cvar 10 | # of Top is overtaken by Object 11 | -------------------------------------------------------------------------------- /examples/class-variables-siblings.rb: -------------------------------------------------------------------------------- 1 | class Parent 2 | @@parent = :strict 3 | def self.parent 4 | @@parent 5 | end 6 | end 7 | class Daughter < Parent 8 | @@parent = :unfair! 9 | @@me = :angelic 10 | def self.me; @@me end 11 | end 12 | class Son < Parent 13 | @@parent = :biased 14 | @@me = :unappreciated 15 | def self.me; @@me end 16 | end 17 | Parent.parent #=> :biased 18 | Daughter.parent #=> :biased 19 | Son.parent #=> :biased 20 | Daughter.me #=> :angelic 21 | Son.me #=> :unappreciated 22 | -------------------------------------------------------------------------------- /examples/closure-binding-nameerror.rb: -------------------------------------------------------------------------------- 1 | # Create a closure referencing an undefined _array_ variable 2 | size = ->{ array.size } 3 | # Define an _array_ variable in the same scope 4 | array = [1,2,3] 5 | # A NameError is raised because _array_ was not 6 | # defined in the closure’s binding 7 | size.call #=> NameError: undefined local variable or method `array' for main:Object 8 | -------------------------------------------------------------------------------- /examples/closure-example.rb: -------------------------------------------------------------------------------- 1 | variable = :first 2 | # Use a lambda literal to create a closure 3 | # whose function is the block and environment 4 | # includes _variable_. Assign the closure 5 | # to a variable. 6 | closure = ->{ "variable = #{variable}" } 7 | # Invoke the closure, using the value 8 | # of _variable_ from its environment 9 | closure.call #=> "variable = first" 10 | # Assign a different value to a variable 11 | # in the closure’s environment 12 | variable = :second 13 | # Re-invoke the closure in the context 14 | # of its current environment, where the 15 | # value of _variable_ is :second 16 | closure.call #=> "variable = second" 17 | -------------------------------------------------------------------------------- /examples/closure-proc-binding.rb: -------------------------------------------------------------------------------- 1 | class Context 2 | @@of = :class 3 | def self.closure 4 | ->{ @@of = :method } 5 | end 6 | end 7 | eval "@@of" #=> uninitialized class variable @@of in Object (NameError) 8 | eval "@@of", Context.closure.binding #=> :class 9 | -------------------------------------------------------------------------------- /examples/closure-with-argument.rb: -------------------------------------------------------------------------------- 1 | array=[*('a'..'c')] #=> ["a", "b", "c"] 2 | element =->(i){ print "#{i}=#{array[i]} " } 3 | # For each element of _array_, call the _element_ 4 | # closure with the index as an argument 5 | array.each_index {|i| element[i] } #=> 0=a 1=b 2=c 6 | -------------------------------------------------------------------------------- /examples/coding-comment.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | __ENCODING__ #=> # 3 | -------------------------------------------------------------------------------- /examples/complex-abs.rb: -------------------------------------------------------------------------------- 1 | (-1.7).abs #=> 1.7 2 | Rational(23, 32).abs #=> (23/32) 3 | Complex(20, 9).abs #=> 21.93171219946131 4 | Complex(-17, 3.5).abs #=> 17.356554957709783 5 | -------------------------------------------------------------------------------- /examples/complex-arg.rb: -------------------------------------------------------------------------------- 1 | (-1.7).arg #=> 3.141592653589793 2 | Rational(23, 32).arg #=> 0 3 | Complex(20, 9).arg #=> 0.4228539261329407 4 | Complex(-17, 3.5).arg #=> 2.938547436336328 5 | -------------------------------------------------------------------------------- /examples/complex-conj.rb: -------------------------------------------------------------------------------- 1 | Complex(13, Rational(1, 2)).conj #=> (13-(1/2)*i) 2 | Complex(7, 6).conj.conj #=> (7+6i) 3 | -------------------------------------------------------------------------------- /examples/complex-constructor.rb: -------------------------------------------------------------------------------- 1 | Complex(42) #=> (42+0i) 2 | Complex(7, 3) #=> (7+3i) 3 | Complex(Rational(3, 4), 4) #=> ((3/4)+4i) 4 | Complex('3+8.2i') #=> (3+8.2i) 5 | -------------------------------------------------------------------------------- /examples/complex-polar.rb: -------------------------------------------------------------------------------- 1 | (-1.7).polar #=> [1.7, 3.141592653589793] 2 | Rational(23, 32).polar #=> [(23/32), 0] 3 | Complex(20, 9).polar #=> [21.93171219946131, 0.4228539261329407] 4 | Complex(-17, 3.5).polar #=> [17.356554957709783, 2.938547436336328] 5 | Complex.polar(*Complex(2,3).polar) #=> (2.0+3.0i) 6 | Complex(-1).polar #=> [1, 3.141592653589793] 7 | -------------------------------------------------------------------------------- /examples/complex-rect.rb: -------------------------------------------------------------------------------- 1 | Complex(23.4, 5.6).rect #=> [23.4, 5.6] 2 | 35.to_c.rectangular #=> [35, 0] 3 | Math::PI.rect #=> [3.141592653589793, 0] 4 | Complex.rect(9, 7) #=> (9+7i) 5 | -------------------------------------------------------------------------------- /examples/conditional-false.rb: -------------------------------------------------------------------------------- 1 | [nil, false].none? #=> true 2 | -------------------------------------------------------------------------------- /examples/conditional-true.rb: -------------------------------------------------------------------------------- 1 | [0, "Erd\u0151s", :false, true, { key: :door }].all? #=> true 2 | -------------------------------------------------------------------------------- /examples/const-missing.rb: -------------------------------------------------------------------------------- 1 | module Roman 2 | ARABIC = {'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 3 | 'C' => 100, 'D' => 500, 'M' => 1000 } 4 | def self.const_missing(name) 5 | digits = [*name.to_s.upcase.chars].reverse.map{|r| ARABIC[r] or super} 6 | digits.map.with_index {|d,i| digits[i.zero? ? i : i-1] > d ? -d : d}.reduce(:+) 7 | end 8 | end 9 | Roman::XLVII #=> 47 10 | -------------------------------------------------------------------------------- /examples/constant-reference.rb: -------------------------------------------------------------------------------- 1 | module Math 2 | PLASTIC = cbrt(0.5 + Rational(1, 6) * sqrt(Rational(23, 3))) + 3 | cbrt(0.5 - Rational(1, 6) * sqrt(Rational(23, 3))) 4 | end 5 | Math::PLASTIC #=> 1.3247179572447458 6 | -------------------------------------------------------------------------------- /examples/control-escape.rb: -------------------------------------------------------------------------------- 1 | "\C-Z".ord #=> 26 2 | "\cx".ord #=> 24 3 | -------------------------------------------------------------------------------- /examples/custom-internal-iterator.rb: -------------------------------------------------------------------------------- 1 | def intermittently(array) 2 | array.each do |element| 3 | sleep rand(10) * (element.size % array.size) 4 | yield element 5 | end 6 | end 7 | 8 | intermittently([191, 2726, 278, 12**10, 182729]) do |element| 9 | puts Time.now.strftime("%H:%M:%S") + " => #{element}" 10 | end 11 | # 00:29:33 => 191 12 | # 00:29:33 => 2726 13 | # 00:29:45 => 278 14 | # 00:30:06 => 61917364224 15 | # 00:30:34 => 182729 16 | -------------------------------------------------------------------------------- /examples/def-explicit-return-multiple.rb: -------------------------------------------------------------------------------- 1 | def elvis 2 | return :to_sender, :hound_dog 3 | # Not reached 4 | end 5 | elvis #=> [:to_sender, :hound_dog] 6 | -------------------------------------------------------------------------------- /examples/def-implicit-return-multiple.rb: -------------------------------------------------------------------------------- 1 | def elvis 2 | [:to_sender, :hound_dog] 3 | end 4 | elvis #=> [:to_sender, :hound_dog] 5 | -------------------------------------------------------------------------------- /examples/def-implicit-return.rb: -------------------------------------------------------------------------------- 1 | def elvis 2 | :to_sender 3 | end 4 | -------------------------------------------------------------------------------- /examples/def-instance-method.rb: -------------------------------------------------------------------------------- 1 | class Dog 2 | def bark 3 | :woof 4 | end 5 | end 6 | Dog.new.bark #=> :woof 7 | -------------------------------------------------------------------------------- /examples/def-non-ascii-name.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | def Π 3 | Math::PI 4 | end 5 | Π #=> 3.141592653589793 6 | -------------------------------------------------------------------------------- /examples/def-singleton-method.rb: -------------------------------------------------------------------------------- 1 | class Dog 2 | def self.breed 3 | [new, new] 4 | end 5 | end 6 | Dog.breed #=> [#, #] 7 | -------------------------------------------------------------------------------- /examples/define-method-class-eval.rb: -------------------------------------------------------------------------------- 1 | Array.class_eval do 2 | define_method(:second, ->{ self.[](1) }) 3 | end 4 | [3, 4, 5].second #=> 4 5 | -------------------------------------------------------------------------------- /examples/define-method.rb: -------------------------------------------------------------------------------- 1 | class Conjure 2 | def self.conjure(name, lamb) 3 | define_method(name, lamb) 4 | end 5 | end 6 | # Define a new instance method with a lambda as its body 7 | Conjure.conjure(:glark, ->{ (3..5).to_a * 2 }) 8 | Conjure.new.glark #=> [3, 4, 5, 3, 4, 5] 9 | -------------------------------------------------------------------------------- /examples/define-singleton-method.rb: -------------------------------------------------------------------------------- 1 | File.define_singleton_method(:match) do |file, pattern| 2 | File.read(file).match(pattern) 3 | end 4 | File.match('/etc/passwd',/root/) #=> # 5 | -------------------------------------------------------------------------------- /examples/defined.rb: -------------------------------------------------------------------------------- 1 | defined? $a #=> nil 2 | defined? 3 + 2 #=> "method" 3 | var = defined? true or nil #=> "true" 4 | defined? var #=> "local-variable" 5 | defined? 1.times { :one } #=> "expression" 6 | defined? yield #=> nil 7 | -------------------------------------------------------------------------------- /examples/dir-glob.rb: -------------------------------------------------------------------------------- 1 | Dir.chdir('/tmp/animals') do 2 | Dir.entries(?.) #=> ["..", "."] 3 | Dir.mkdir('extinct') 4 | %w{ants hippopotamus elephants arachnids koalas accounts.csv 5 | accounts.csv.bak visitors.log rota-2010 extinct/velociraptor 6 | extinct/quagga extinct/aurochs extinct/dodo}.each{|file| open(file, ?w){} } 7 | Dir.glob('*ants') #=> ["elephants", "ants"] 8 | Dir.glob('rota-????') #=> ["rota-2010"] 9 | Dir.glob('a*s') #=> ["ants", "arachnids"] 10 | Dir.glob('**/a*s') #=> ["ants", "arachnids", "extinct/aurochs"] 11 | Dir.glob('extinct/*o[dc]*') #=> ["extinct/aurochs", "extinct/dodo", "extinct/velociraptor"] 12 | Dir.glob('{*.*,rota-201[0-9]}') 13 | #=> ["accounts.csv", "accounts.csv.bak", "visitors.log", "rota-2010"] 14 | end 15 | -------------------------------------------------------------------------------- /examples/divmod.rb: -------------------------------------------------------------------------------- 1 | 90.divmod 9 #=> [10, 0] 2 | 772.divmod 6 #=> [128, 4] 3 | 40_500.remainder 1_000 #=> 500 4 | -------------------------------------------------------------------------------- /examples/double-quoted-string-literal-q.rb: -------------------------------------------------------------------------------- 1 | %&"& #=> '"' 2 | %Q;\ 3 | #{2**2}; #=> " 4" 4 | %Q<\u0062old> #=> "bold" 5 | -------------------------------------------------------------------------------- /examples/each-selector.rb: -------------------------------------------------------------------------------- 1 | (-2..2).each #=> # 2 | (-2..2).each {|n| print " <#{n}> "} 3 | # <-2> <-1> <0> <1> <2> 4 | -------------------------------------------------------------------------------- /examples/each_-selector.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | "Böhm-Bawerk".each_line.to_a 3 | #=> ["Böhm-Bawerk"] 4 | "Böhm-Bawerk".each_char.to_a 5 | #=> ["B", "ö", "h", "m", "-", "B", "a", "w", "e", "r", "k"] 6 | "Böhm-Bawerk".each_byte.to_a 7 | #=> [66, 195, 182, 104, 109, 45, 66, 97, 119, 101, 114, 107] 8 | "Böhm-Bawerk".each_codepoint.to_a 9 | #=> [66, 246, 104, 109, 45, 66, 97, 119, 101, 114, 107] 10 | -------------------------------------------------------------------------------- /examples/element-set-selector.rb: -------------------------------------------------------------------------------- 1 | tower = 'Tower of Pisa' 2 | tower[/\w+$/] = 'Babel' 3 | tower #=> "Tower of Babel" 4 | tower[-5..-1] = 'London' 5 | tower #=> "Tower of London" 6 | tower = tower.split(//) 7 | tower[0..4] = %w{C i t y} 8 | tower.join #=> "City of London" 9 | -------------------------------------------------------------------------------- /examples/empty-splat.rb: -------------------------------------------------------------------------------- 1 | a, *, b = *(1..5) 2 | a #=> 1 3 | b #=> 5 4 | -------------------------------------------------------------------------------- /examples/end-block.rb: -------------------------------------------------------------------------------- 1 | puts 1 2 | END { puts 2 } 3 | puts 3 4 | # Output: 5 | # 1 6 | # 3 7 | # 2 8 | -------------------------------------------------------------------------------- /examples/ensure-clause.rb: -------------------------------------------------------------------------------- 1 | require 'yaml' 2 | YAML_FILE = 'tasks.yaml' 3 | begin 4 | tasks = ['Water plants', 'Plant water'] 5 | # ... 6 | tasks << 'Practice pentatonic scales' 7 | raise RuntimeError unless tasks.include?('Run 5 miles') 8 | rescue RuntimeError 9 | tasks << 'Run 5 miles' 10 | ensure 11 | File.open(YAML_FILE,'w') {|f| YAML.dump(tasks, f)} 12 | end 13 | YAML.load(File.read YAML_FILE) #=> ["Water plants", "Plant water", 14 | # "Practice pentatonic scales", "Run 5 miles"] 15 | -------------------------------------------------------------------------------- /examples/enu-any-all-none-one.rb: -------------------------------------------------------------------------------- 1 | digits = 0..9 2 | digits.all?{|d| d < 10} #=> true 3 | digits.none?{|d| (d ** 2) > 10} #=> false 4 | digits.one?{|d| d == 3} #=> true 5 | digits.any?{|d| d == 3} #=> true 6 | (1...Float::INFINITY).any?{|d| d % 10 == 2} #=> true 7 | [5, Rational(8, 2), ''[1], :nil].all? #=> false 8 | users = IO.foreach('/etc/passwd').map{|user| user.split(/:/)} 9 | users.all?{|u| u.last.start_with?(?/)} and users.one?{|u| u.first == 'root'} #=> true 10 | -------------------------------------------------------------------------------- /examples/enu-chunk.rb: -------------------------------------------------------------------------------- 1 | Math::PI.to_s.scan(/\d/).map(&:to_i).chunk(&:even?).map(&:last) 2 | #=> [[3, 1], [4], [1, 5, 9], [2, 6], [5, 3, 5], [8], [9, 7, 9, 3]] 3 | ROWS, COLS = 9, 17 4 | grid = ROWS.times.map{ Array.new(COLS, ' ') } 5 | (2..40).map{|n| Math.sin(n) ** 2}.chunk{|n| Math.log10(n).to_i}.each_with_index do |(log, ns), i| 6 | ROWS.pred.downto(ROWS-ns.size){|row| grid[row][i] = " * "} 7 | (grid[ROWS] ||= []) << "%#2d " % log 8 | end 9 | grid.each{|row| puts row.join} 10 | # * * 11 | # * * 12 | # * * 13 | # * * 14 | # * * 15 | # * * 16 | # * * 17 | # * * * * * * * * 18 | # * * * * * * * * * * * * * * * * * 19 | # 0 -1 0 -1 0 -1 0 -1 0 -4 0 -1 0 -1 0 -1 0 20 | -------------------------------------------------------------------------------- /examples/enu-count.rb: -------------------------------------------------------------------------------- 1 | enu = [1, 1, 3, 5, 5, 5, 5, 6, 8, 10, 12, -12, 1, 2] 2 | enu.count #=> 14 3 | enu.count(1.0) #=> 3 4 | enu.count(7) #=> 0 5 | enu.count{|n| n.odd? and n > 0} #=> 8 6 | enu.clear.count #=> 0 7 | [%w{a b}, %w{c d}].count([?a, ?b]) #=> 1 8 | -------------------------------------------------------------------------------- /examples/enu-cycle.rb: -------------------------------------------------------------------------------- 1 | [].cycle{ raise } #=> nil 2 | [:a, :b, :c].cycle(2).to_a #=> [:a, :b, :c, :a, :b, :c] 3 | (1..100).cycle(100).with_index do |n,i| 4 | break [n,i] if (n * i).to_s(16) =~ /^([[:xdigit:]]{2})\1$/ 5 | end #=> [58, 257] 6 | -------------------------------------------------------------------------------- /examples/enu-detect.rb: -------------------------------------------------------------------------------- 1 | (?b..?r).detect{|e| e =~ /[aeiou]/} #=> "e" 2 | (?b..?r).detect{|e| e =~ /[[:upper:]]/} #=> nil 3 | [Rational(1,10), Rational(7,10), Rational(4,10)].find(->{ 10 }){|e| e > 10} #=> 10 4 | -------------------------------------------------------------------------------- /examples/enu-enumerator-instantiation.rb: -------------------------------------------------------------------------------- 1 | "Once bitten, twice shy".to_enum(:bytes).first(5) 2 | #=> [79, 110, 99, 101, 32] 3 | Enumerator.new do |yielder| 4 | (1..Float::INFINITY).each do |n| 5 | yielder << n if n.odd? 6 | end 7 | end.first(5) #=> [1, 3, 5, 7, 9] 8 | -------------------------------------------------------------------------------- /examples/enu-feed.rb: -------------------------------------------------------------------------------- 1 | o = Object.new 2 | $y = [] 3 | def o.each 4 | 3.times.map{|n| yield n} 5 | end 6 | e = o.to_enum 7 | e.next #=> 0 8 | e.feed 0 #=> nil 9 | e.next #=> 1 10 | e.next #=> 2 11 | (e.next rescue $!).result #=> [0. nil, nil] 12 | -------------------------------------------------------------------------------- /examples/enu-find-index.rb: -------------------------------------------------------------------------------- 1 | (:aa..:zz).find_index(:az) #=> 25 2 | stages = {baby: :infant, infant: :toddler, toddler: :preteen, teen: :adult} 3 | stages.find_index{|from, to| from == :toddler} #=> 2 4 | stages.find_index{|from, to| from == :adult} #=> nil 5 | -------------------------------------------------------------------------------- /examples/enu-first-take-drop.rb: -------------------------------------------------------------------------------- 1 | digits = 0..9 2 | digits.first #=> 0 3 | digits.first(3) #=> [0, 1, 2] 4 | digits.drop(3) #=> [3, 4, 5, 6, 7, 8, 9] 5 | digits.take(30) 6 | #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 7 | digits.select{|e| e.even? and e.odd?}.first(2) #=> [] 8 | -------------------------------------------------------------------------------- /examples/enu-grep.rb: -------------------------------------------------------------------------------- 1 | Enumerable.instance_methods.grep(/while/) 2 | #=> [:take_while, :drop_while] 3 | (1..100).grep(5..7) 4 | #=> [5, 6, 7] 5 | (1..1000).grep(->(e){ e.to_s(2) =~ /^110+11$/}) 6 | #=> [27, 51, 99, 195, 387, 771] 7 | -------------------------------------------------------------------------------- /examples/enu-include.rb: -------------------------------------------------------------------------------- 1 | [/a/, :a, ?a].include? /a/ #=> true 2 | [Dir.home, __FILE__].include? 47 #=> false 3 | (?~ * 10).include? ?~ #=> true 4 | 1.0.step(2.0, 0.1).member? 1.6 #=> true 5 | [[0,1]].include? 0 #=> false 6 | {a:1}.include? :a #=> true 7 | {a:1}.include? 1 #=> false 8 | -------------------------------------------------------------------------------- /examples/enu-inject.rb: -------------------------------------------------------------------------------- 1 | %w{a b c d}.reduce(:+) #=> "abcd" 2 | (2..8).reverse_each.inject(:-) #=> -19 3 | [[:a, 4], [:b, 12], [:c, 9]].reduce(1){|acc, el| acc * el.last} #=> 432 4 | [{joe: 27}, {bob: 23}, {jim: 40}, {jolene: 18}].reduce :merge 5 | #=> {:joe=>27, :bob=>23, :jim=>40, :jolene=>18} 6 | Dir["#{Dir.home}/.*"].reduce do |newest, file| 7 | File.file?(file) && File.mtime(newest) < File.mtime(file) ? file : newest 8 | end #=> "/home/run/.xsession-errors 9 | -------------------------------------------------------------------------------- /examples/enu-iterate.rb: -------------------------------------------------------------------------------- 1 | $places = %w{Agartha Atlantis Avalon Camelot Eden 2 | El_Dorado Shangri-La Thule Utopia Valhalla} 3 | $places.each_with_index.map{|place, index| "#{index}:#{place.size}"} 4 | #=> ["0:7", "1:8", "2:6", "3:7", "4:4", "5:9", "6:10", "7:5", "8:6", "9:8"] 5 | $places.reverse_each{|place| print place[0]} 6 | # VUTSEECAAA 7 | $places.each_with_object({}){|place,vowels| vowels[place] = place.downcase.count('aeiou')} 8 | #=> {"Agartha"=>3, "Atlantis"=>3, "Avalon"=>3, "Camelot"=>3, "Eden"=>2, "El_Dorado"=>4, 9 | #=> "Shangri-La"=>3, "Thule"=>2, "Utopia"=>4, "Valhalla"=>3} 10 | class Places 11 | def each 12 | $places.group_by{|place| place[0]}.each{|letter, names| yield letter, *names} 13 | end 14 | end 15 | Places.new.extend(Enumerable).each_entry{|places| print " #{places.first}:#{places[1..-1].size}"} 16 | # A:3 C:1 E:2 S:1 T:1 U:1 V:1 17 | -------------------------------------------------------------------------------- /examples/enu-map.rb: -------------------------------------------------------------------------------- 1 | (?a..?f).map &:upcase 2 | #=> ["A", "B", "C", "D", "E", "F"] 3 | (10..20).map{|n| n**2 } 4 | #=> [100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400] 5 | { 'google.com' => 'Google', 6 | 'ruby-lang.org' => 'Ruby', 7 | 'wikipedia.org' => 'Wikipedia'}.map do |host, anchor| 8 | "#{anchor}" 9 | end 10 | #=> ["Google", "Ruby", 11 | #=> "Wikipedia"] 12 | [10..20, 20..30, 30..40, 40..50].collect{|r| r.to_a.sample} 13 | #=> [16, 30, 36, 44] 14 | shells = IO.foreach('/etc/passwd').flat_map{|l| l.chomp.split(/:/).values_at(0,-1)} 15 | Hash[*shells]['kernoops'] #=> "/bin/false" 16 | -------------------------------------------------------------------------------- /examples/enu-min-max-by.rb: -------------------------------------------------------------------------------- 1 | [300, 92, 827_99, -45, 300, 1].minmax_by(&:magnitude) #=> [1, 82799] 2 | languages = %w{Ruby Haskell Scala Clojure Perl Python Lisp Smalltalk} 3 | languages.min_by(&:size) #=> "Ruby" 4 | languages.max_by{|l| l.codepoints.reduce(:+)} #=> "Smalltalk" 5 | languages.minmax_by{|l| l.ord } #=> ["Clojure", "Scala"] 6 | languages.sort.minmax_by {|l| languages.count{|e| l.start_with?(e[0])}} 7 | #=> ["Clojure", "Perl"] 8 | -------------------------------------------------------------------------------- /examples/enu-min-max.rb: -------------------------------------------------------------------------------- 1 | [300, 92, 827_99, -45, 300, 1].minmax #=> [-45, 82799] 2 | languages = %w{Ruby Haskell Scala Clojure Perl Python Lisp Smalltalk} 3 | languages.min #=> "Clojure" 4 | languages.max #=> "Smalltalk" 5 | languages.min{ +1 } #=> "Ruby" 6 | languages.minmax{|a,b| a.ord <=> b.ord } #=> ["Clojure", "Scala"] 7 | languages.sort.minmax do |a,b| 8 | languages.count{|l| l.start_with?(a[0])} <=> languages.count{|l| l.start_with?(b[0])} 9 | end #=> ["Clojure", "Perl"] 10 | -------------------------------------------------------------------------------- /examples/enu-next.rb: -------------------------------------------------------------------------------- 1 | e = (1..3).to_enum 2 | 3.times{ print e.next } # 123 3 | e.rewind 4 | [e.peek, e.next, e.peek, e.peek, e.next] #=> [1, 1, 2, 2, 2] 5 | -------------------------------------------------------------------------------- /examples/enu-next_values.rb: -------------------------------------------------------------------------------- 1 | o = Object.new 2 | def o.each 3 | yield 1 4 | yield 2, 3 5 | yield 6 | yield nil 7 | end 8 | e = o.to_enum 9 | loop.map{ e.next } #=> [1, [2, 3], nil, nil] 10 | e.rewind 11 | loop.map{ e.next_values } #=> [[1], [2, 3], [], [nil]] 12 | e.rewind 13 | 2.times.map{ [e.peek_values, e.next] } 14 | #=> [[[1], 1], [[2, 3], [2, 3]]] 15 | -------------------------------------------------------------------------------- /examples/enu-partition-group-by.rb: -------------------------------------------------------------------------------- 1 | square, nonsquare = (1..25).partition{|n| Math.sqrt(n) == Math.sqrt(n).to_i} 2 | #=> [[1, 4, 9, 16, 25], 3 | #=> [2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24]] 4 | (1..10).group_by{|n| 10.lcm n} 5 | #=> {10=>[1, 2, 5, 10], 30=>[3, 6], 20=>[4], 70=>[7], 40=>[8], 90=>[9]} 6 | String.instance_methods.group_by{|m| String.instance_method(m).arity}.map{|a,m| [a, m.size]} 7 | #=> [[1, 42], [0, 71], [-1, 47], [2, 9]] 8 | -------------------------------------------------------------------------------- /examples/enu-select-reject.rb: -------------------------------------------------------------------------------- 1 | (1...1000).select{|n| n.to_s(16).end_with?('ef')} #=> [239, 495, 751] 2 | fruits = {raspberry: :red, grape: [:white, :black], banana: :yellow, orange: :orange} 3 | fruits.select{|fruit, colour| fruits.key?(colour)} #=> {:orange => :orange} 4 | (0..9).reject(&:even?) #=> [1, 3, 5, 7, 9] 5 | -------------------------------------------------------------------------------- /examples/enu-slice-before.rb: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | Math::PI.to_s.scan(/\d/).map(&:to_i).slice_before(&:even?).to_a 3 | #=> [[3, 1], [4, 1, 5, 9], [2], [6, 5, 3, 5], [8, 9, 7, 9, 3]] 4 | IO.foreach('/usr/share/dict/words').slice_before(/^[[:upper:]]$/).map{|w| w.last.chomp}[1..5] 5 | #=> ["Aztlan's", "Byzantium's", "Czerny's", "Düsseldorf", "Ezra's"] 6 | (?a..?z).slice_before{|l| %w{a e i o u}.include? l}.to_a 7 | #=> [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l", "m", "n"], 8 | # ["o", "p", "q", "r", "s", "t"], ["u", "v", "w", "x", "y", "z"]] 9 | -------------------------------------------------------------------------------- /examples/enu-slice-cons.rb: -------------------------------------------------------------------------------- 1 | plants = [:Hornworts, :Mosses, :Liverworts, :Conifers, :Cycads, :flowering_plants] 2 | plants.each_slice(1).to_a 3 | #=> [[:Hornworts], [:Mosses], [:Liverworts], [:Conifers], [:Cycads], [:flowering_plants]] 4 | plants.each_cons(1).to_a 5 | #=> [[:Hornworts], [:Mosses], [:Liverworts], [:Conifers], [:Cycads], [:flowering_plants]] 6 | plants.each_slice(2).to_a 7 | #=> [[:Hornworts, :Mosses], [:Liverworts, :Conifers], [:Cycads, :flowering_plants]] 8 | plants.each_cons(2).to_a 9 | #=> [[:Hornworts, :Mosses], [:Mosses, :Liverworts], [:Liverworts, :Conifers], 10 | #=> [:Conifers, :Cycads], [:Cycads, :flowering_plants]] 11 | plants.each_slice(4).to_a.flatten.count(:Liverworts) #=> 1 12 | plants.each_cons(4).to_a.flatten.count(:Liverworts) #=> 3 13 | plants.each_slice(5).count #=> 2 14 | plants.each_cons(5).count #=> 2 15 | -------------------------------------------------------------------------------- /examples/enu-sort.rb: -------------------------------------------------------------------------------- 1 | gods = %w{Aphrodite Demeter Ares Eros Apollo Hades Dionysus 2 | Artemis Zeus Hera Hermes Poseidon Athena Hestia Hephaestus} 3 | gods.sort #=>["Aphrodite", "Apollo", "Ares", "Artemis", "Athena", "Demeter", "Dionysus", 4 | #=> "Eros", "Hades", "Hephaestus", "Hera", "Hermes", "Hestia", "Poseidon", "Zeus"] 5 | gods.sort{|a, b| a.length <=> b.length} 6 | #=> ["Hera", "Zeus", "Ares", "Eros", "Hades", "Apollo", "Hermes", "Athena", "Hestia", 7 | #=> "Demeter", "Artemis", "Poseidon", "Dionysus", "Aphrodite", "Hephaestus"] 8 | Hash[*gods.zip(%w{f f m m m m m f m f m m f f m}).flatten].sort_by(&:reverse).map(&:first) 9 | #=> ["Aphrodite", "Artemis", "Athena", "Demeter", "Hera", "Hestia", "Apollo", "Ares", 10 | #=> "Dionysus", "Eros", "Hades", "Hephaestus", "Hermes", "Poseidon", "Zeus"] 11 | class String 12 | def <=>(o) 13 | reverse.ord <=> o.reverse.ord 14 | end 15 | end 16 | gods.sort #=> ["Hera", "Hestia", "Athena", "Aphrodite", "Poseidon", "Apollo", "Demeter", 17 | #=> "Artemis", "Zeus", "Dionysus", "Hermes", "Hades", "Eros", "Ares", "Hephaestus"] 18 | -------------------------------------------------------------------------------- /examples/enu-stopiteration.rb: -------------------------------------------------------------------------------- 1 | e = [:rinse, :repeat].to_enum 2 | e.next #=> :rinse 3 | e.next #=> :repeat 4 | begin 5 | e.next 6 | rescue StopIteration => ex 7 | ex.result #=> [:rinse, :repeat] 8 | end 9 | e.rewind 10 | loop{ p e.next } 11 | # :rinse 12 | # :repeat 13 | -------------------------------------------------------------------------------- /examples/enu-take-drop-while.rb: -------------------------------------------------------------------------------- 1 | digits = 1..9 2 | require 'prime' 3 | square_free = ->(n){ n.prime_division.all?{|a,b| b == 1} } 4 | digits.take_while(&square_free) #=> [1, 2, 3] 5 | digits.drop_while(&square_free) #=> [4, 5, 6, 7, 8, 9] 6 | -------------------------------------------------------------------------------- /examples/enu-zip.rb: -------------------------------------------------------------------------------- 1 | [:a, :b, :c].zip #=> [[:a], [:b], [:c]] 2 | [:a].zip([:b, :c], [:d, :e, :f]) #=> [[:a, :b, :d]] 3 | [:a, :b, :c].zip([:d], [:e, :f]) #=> [[:a, :d, :e], [:b, nil, :f], [:c, nil, nil]] 4 | digits = 1..3 5 | sin, cos, tan = %w{sin cos tan}.map{|m| digits.map{|n| Math.send(m, n * Math::PI/180)}} 6 | digits.zip(sin, cos, tan) 7 | #=> [[1, 0.01745240643728351, 0.9998476951563913, 0.017455064928217585], 8 | #=> [2, 0.03489949670250097, 0.9993908270190958, 0.03492076949174773], 9 | #=> [3, 0.05233595624294383, 0.9986295347545738, 0.052407779283041196]] 10 | -------------------------------------------------------------------------------- /examples/enumerable-to-enum.rb: -------------------------------------------------------------------------------- 1 | latin = "Tu ne cede malis, sed contra audentior ito" 2 | char_string = latin.to_enum(:each_char) 3 | vowels, consonants = char_string.partition{|char| char =~ /[aeiou]/} 4 | vowels #=> 5 | # ["u", "e", "e", "e", "a", "i", "e", "o", "a", "a", "u", "e", "i", "o", "i", "o"] 6 | -------------------------------------------------------------------------------- /examples/enumerating-subclasses.rb: -------------------------------------------------------------------------------- 1 | require 'tempfile' 2 | class Class 3 | def children 4 | ObjectSpace.each_object(Class).select{|c| c < self} 5 | end 6 | end 7 | Delegator.children #=> [SimpleDelegator, Tempfile, #] 8 | -------------------------------------------------------------------------------- /examples/equal-equal-selector.rb: -------------------------------------------------------------------------------- 1 | 1 == 1 #=> true 2 | 1 == 1.0 #=> true 3 | 1 == :one #=> false 4 | -------------------------------------------------------------------------------- /examples/equal-tilde-selector.rb: -------------------------------------------------------------------------------- 1 | "Hieronymus Bosch" =~ /Ron/i #=> 3 2 | "Jheronimus van Aken" =~ /Ron/i #=> 3 3 | /hero/ =~ "Jheronimus van Aken" #=> 1 4 | /heretic/ =~ "Hieronymus Bosch" #=> nil 5 | -------------------------------------------------------------------------------- /examples/extend-class.rb: -------------------------------------------------------------------------------- 1 | module Instances 2 | def instances 3 | ObjectSpace.each_object(self).to_a 4 | end 5 | end 6 | harmonic_sequence = 1.upto(10).map{|d| Rational(1,d)} 7 | def pell(n) 8 | return n if [0, 1].include?(n) 9 | 2 * pell(n-1) + pell(n-2) 10 | end 11 | approx_sqrt_2 = (1..20).map{|n| Rational(pell(n-1) + pell(n), pell(n))} 12 | Rational.extend(Instances) 13 | Rational.instances.size #=> 30 14 | -------------------------------------------------------------------------------- /examples/file-expand-path.rb: -------------------------------------------------------------------------------- 1 | Dir.chdir('/etc') do 2 | File.expand_path '/etc/resolv.conf' #=> "/etc/resolv.conf" 3 | File.expand_path 'resolv.conf' #=> "/etc/resolv.conf" 4 | File.expand_path '../var/log/messages' #=> "/var/log/messages" 5 | File.expand_path './filesystems', '/proc' #=> "/proc/filesystems" 6 | File.expand_path '~/.bashrc' #=> "/home/run/.bashrc" 7 | ENV['HOME'] = '/tmp' 8 | File.expand_path '~/.bashrc' #=> "/tmp/.bashrc" 9 | File.expand_path '~root' #=> "/root" 10 | end 11 | 12 | -------------------------------------------------------------------------------- /examples/file-read.rb: -------------------------------------------------------------------------------- 1 | File.read('/etc/timezone') #=> "Europe/London\n" 2 | File.read('/etc/timezone', 6) #=> "Europe" 3 | File.read('/etc/timezone', 6, 7) #=> "London" 4 | -------------------------------------------------------------------------------- /examples/file-realpath.rb: -------------------------------------------------------------------------------- 1 | Dir.chdir('/etc') do 2 | File.realpath '/etc/resolv.conf' #=> "/etc/resolv.conf" 3 | File.realpath 'resolv.conf' #=> "/etc/resolv.conf" 4 | File.readlink '/etc/alternatives/www-browser' #=> "/usr/bin/w3m" 5 | File.realpath '../etc/alternatives/../alternatives/ruby' 6 | # No such file or directory - /etc/alternatives/ruby (Errno::ENOENT) 7 | File.realdirpath '../etc/alternatives/../alternatives/ruby' #=> "/etc/alternatives/ruby" 8 | end 9 | 10 | -------------------------------------------------------------------------------- /examples/file-symlink.rb: -------------------------------------------------------------------------------- 1 | link, target = '/tmp/link', '/tmp/target' 2 | File.unlink(link) if File.exist?(link) 3 | open(target, mode: ?w) {} 4 | File.symlink(target, link) 5 | File.symlink?(target) #=> false 6 | File.symlink?(link) #=> true 7 | File.readlink(link) #=> "/tmp/target" 8 | -------------------------------------------------------------------------------- /examples/float-limits.rb: -------------------------------------------------------------------------------- 1 | Float::MAX + 1 == Float::MAX 2 | Float::MAX * 2 == Float::INFINITY 3 | Float::MIN - 60_000 == -60_000 4 | -------------------------------------------------------------------------------- /examples/float-roundoff.rb: -------------------------------------------------------------------------------- 1 | 0.1 * 3 #=> 0.30000000000000004 2 | 0.1 * 3 == 0.3 #=> false 3 | -------------------------------------------------------------------------------- /examples/for-loop.rb: -------------------------------------------------------------------------------- 1 | string = '' 2 | for element in 97..100 3 | string << element if element.odd? 4 | end 5 | string #=> "ac" 6 | -------------------------------------------------------------------------------- /examples/gcdlcm.rb: -------------------------------------------------------------------------------- 1 | 456.gcd 320 #=> 8 2 | 29.gcd 19 #=> 1 3 | 4392.lcm 282 #=> 206424 4 | 10.gcdlcm 4 #=> [2, 20] 5 | -------------------------------------------------------------------------------- /examples/global-variables.rb: -------------------------------------------------------------------------------- 1 | $omnipresent #=> nil 2 | class Diety 3 | $omnipresent = :yes 4 | def preternatural? 5 | $omnipresent == :yes 6 | end 7 | end 8 | $omnipresent #=> :yes 9 | Diety.new.preternatural? #=> true 10 | -------------------------------------------------------------------------------- /examples/greater-than-selector.rb: -------------------------------------------------------------------------------- 1 | 42 > 43 #=> false 2 | 10 > 1 #=> true 3 | 'a' > 'aa' #=> false 4 | 'z' > 'Z' #=> true 5 | -------------------------------------------------------------------------------- /examples/hash-coerce.rb: -------------------------------------------------------------------------------- 1 | {}.to_hash #=> {} 2 | Hash[*(1..6)] #=> {1=>2, 3=>4, 5=>6} 3 | {a: :value, b: [:key]}.to_a #=> [[:a, :value], [:b, [:key]]] 4 | Hash.try_convert(try: :again) #=> {:try=>:again} 5 | Hash.try_convert([:element]) #=> nil 6 | h = { Object.new => Rational(2, 3) } 7 | h[:h] = h 8 | h.to_s #=> "{#=>(2/3), :h=>{...}}" 9 | -------------------------------------------------------------------------------- /examples/hash-default-value.rb: -------------------------------------------------------------------------------- 1 | h = {a: 1, b: 2} 2 | h[:c] #=> nil 3 | h.default #=> nil 4 | h = Hash.new(0) 5 | h[:c] #=> 0 6 | h[:c] = 3 7 | h[:c] #=> 3 8 | h.default = ?? 9 | h[:d] #=> "?" 10 | require 'prime' 11 | next_prime = Hash.new do |h, k| 12 | prime = k.succ 13 | prime += 1 until prime.prime? 14 | h[k] = prime 15 | end 16 | [12, 17, 48, 200].map{|n| next_prime[n]} #=> [13, 19, 53, 211] 17 | next_prime #=> {12=>13, 17=>19, 48=>53, 200=>211} 18 | -------------------------------------------------------------------------------- /examples/hash-delete.rb: -------------------------------------------------------------------------------- 1 | elements = {H: :hydrogen, Li: :lithium, Na: :sodium, K: :potassium, 2 | Rb: :rubidium, Cs: :caesium, Fr: :francium} 3 | elements.delete(:Fr) #=> :francium 4 | elements.delete(:O){ false } #=> false 5 | elements.shift #=> [:H, :hydrogen] 6 | elements.delete_if{|sym, name| sym.size == 1} 7 | #=> {:Li=>:lithium, :Na=>:sodium, :Rb=>:rubidium, :Cs=>:caesium} 8 | elements.reject{|sym, name| name =~ /um/} #=> {} 9 | elements.select!{|sym, name| name.to_s.end_with?(?m)} #=> nil 10 | elements.replace({li: 'list item', p: 'paragraph', hr: 'horizontal rule'}) 11 | #=> {:li=>"list item", :p=>"paragraph", :hr=>"horizontal rule"} 12 | -------------------------------------------------------------------------------- /examples/hash-equal.rb: -------------------------------------------------------------------------------- 1 | {} == {} #=> true 2 | {foo: :bar, "foo" => :bar} == {foo: :bar, "foo" => :bar} #=> true 3 | {a: 1, b: 2} == {b: 2, a: 1} #=> true 4 | {a: 1, b: 2} == {a: 1} #=> false 5 | Hash.new(8) == {} #=> true 6 | {key: :value} == [:key, :value] #=> false 7 | a = {a: 1} 8 | a[:b] = a 9 | a == a.merge(b: a) #=> true 10 | -------------------------------------------------------------------------------- /examples/hash-identity.rb: -------------------------------------------------------------------------------- 1 | rat = {Rational(1,2) => 0.5, Rational(3,4) => 0.75} 2 | rat[Rational(3,4)] = '3/4' 3 | rat #=> {(1/2)=>0.5, (3/4)=>"3/4"} 4 | rat.compare_by_identity[Rational(1,2)] = '1/2' 5 | rat #=> {(1/2)=>0.5, (3/4)=>"3/4", (1/2)=>"1/2"} 6 | rat.compare_by_identity? #=> true 7 | feet = {cat: :paws, pigs: :hooves, bird: :claws}.compare_by_identity 8 | feet[:pigs] = :cloven_hooves 9 | feet #=> {:cat=>:paws, :pigs=>:cloven_hooves, :bird=>:claws} 10 | -------------------------------------------------------------------------------- /examples/hash-iteration.rb: -------------------------------------------------------------------------------- 1 | music = {LP: :long_play, EP: :extended_play, CD: :compact_disc} 2 | music.each.map{|k, v| "#{k} means '#{v}'"} 3 | ["LP means 'long_play'", "EP means 'extended_play'", "CD means 'compact_disc'"] 4 | music.each_key{|acronym| print acronym} 5 | # LPEPCD 6 | #=> {:LP=>:long_play, :EP=>:extended_play, :CD=>:compact_disc} 7 | -------------------------------------------------------------------------------- /examples/hash-keys.rb: -------------------------------------------------------------------------------- 1 | snomed = {T: :Topography, M: :Morphology, L: :Living_organisms, C: :Chemical, 2 | F: :Fever, J: :Occupation, D: :Diagnosis, P: :Procedure, 3 | A: :Physical, S: :Social_context, G: :General} 4 | snomed.key :General #=> :G 5 | snomed.key? :D #=> true 6 | snomed.include? :E #=> false 7 | snomed.keys #=> [:T, :M, :L, :C, :F, :J, :D, :P, :A, :S, :G] 8 | snomed.each_key.reject{|k| snomed[k] =~ /^#{k}/} #=> [:J, :A] 9 | -------------------------------------------------------------------------------- /examples/hash-literals.rb: -------------------------------------------------------------------------------- 1 | {lemon: :yellow, orange: :orange, apple: [:red, :green]} 2 | #=> {:lemon=>:yellow, :orange=>:orange, :apple=>[:red, :green]} 3 | {?a => :vowel, ?b => :consonant, ?c => :consonant, 4 | ?d => :consonant, ?e => :vowel, ?f => :consonant} 5 | #=> {"a"=>:vowel, "b"=>:consonant, "c"=>:consonant, 6 | "d"=>:consonant, "e"=>:vowel, "f"=>:consonant} 7 | {:london => :england, :londonderry => :ireland, london: :ontario} 8 | #=> {:london=>:ontario, :londonderry=>:ireland} 9 | -------------------------------------------------------------------------------- /examples/hash-lookup.rb: -------------------------------------------------------------------------------- 1 | vitamins = {apricot: :a, ham: :b1, cabbage: :c, spinach: :k} 2 | vitamins[:apricot] #=> :a 3 | vitamins.fetch(:pizza, '???') #=> "???" 4 | vitamins.fetch(:kale){|food| [:a, :c, :d, :e, :k].sample} #=> :c 5 | vitamins.values_at(:spinach, :cheese, :ham) #=> [:k, nil, :b1] 6 | vitamins.assoc(:cabbage) #=> [:cabbage, :c] 7 | vitamins.rassoc(:c) #=> [:cabbage, :c] 8 | -------------------------------------------------------------------------------- /examples/hash-merge.rb: -------------------------------------------------------------------------------- 1 | currencies = {ruble: :Russia, dollar: :Fiji, euro: :Malta, zloty: :Poland} 2 | currencies.update(dollar: :Taiwan, euro: :Spain, franc: :Switzerland) 3 | #=> {:ruble=>:Russia, :dollar=>:Taiwan, :euro=>:Spain, 4 | #=> :zloty=>:Poland, :franc=>:Switzerland} 5 | currencies.merge(krona: :Sweden, won: :South_Korea, euro: :Italy){|currency, old, new| old} 6 | #=> {:ruble=>:Russia, :dollar=>:Taiwan, :euro=>:Spain, :zloty=>:Poland, 7 | #=> :franc=>:Switzerland, :krona=>:Sweden, :won=>:South_Korea} 8 | -------------------------------------------------------------------------------- /examples/hash-rehash.rb: -------------------------------------------------------------------------------- 1 | coords = {[0,0] => :origin} 2 | treasure = [32,19] 3 | coords[treasure] = :gold 4 | treasure[-1] += 1 5 | coords #=> {[0, 0]=>:origin, [32, 20]=>:gold} 6 | coords[treasure] #=> nil 7 | coords.rehash 8 | coords[treasure] #=> :gold 9 | -------------------------------------------------------------------------------- /examples/hash-size.rb: -------------------------------------------------------------------------------- 1 | h = {} 2 | h.size #=> 0 3 | h.empty? #=> true 4 | h[3] = 4 5 | h[4] = 5 6 | h[5] = nil 7 | h.size #=> 3 8 | h.empty? #=> false 9 | -------------------------------------------------------------------------------- /examples/hash-sort.rb: -------------------------------------------------------------------------------- 1 | old_capitals = {Scotland: [:Scone, :Edinburgh], Denmark: [:Roskilde, :Copenhagen], 2 | Finalnd: [:Turku, :Helsinki], Sweden: [:Sigtuna, :Stockholm]} 3 | old_capitals.sort 4 | #=> [[:Denmark, [:Roskilde, :Copenhagen]], [:Finalnd, [:Turku, :Helsinki]], 5 | #=> [:Scotland, [:Scone, :Edinburgh]], [:Sweden, [:Sigtuna, :Stockholm]]] 6 | {}.sort #=> [] 7 | -------------------------------------------------------------------------------- /examples/hash-store.rb: -------------------------------------------------------------------------------- 1 | h = {} 2 | h[:key] = :value #=> :value 3 | h.store("Key", "Value") #=> "Value" 4 | h["Key"] = "Ring" #=> "Ring" 5 | h #=> {:key=>:value, "Key"=>"Ring"} 6 | -------------------------------------------------------------------------------- /examples/hash-transform.rb: -------------------------------------------------------------------------------- 1 | demonyms = {Barbados: :Bajan, Spain: :Spaniard, Ireland: :Irish, 2 | Australia: [:Australian, :Aussie], Peru: :Peruvian} 3 | demonyms.flatten 4 | #=> [:Barbados, :Bajan, :Spain, :Spaniard, :Ireland, :Irish, 5 | #=> :Australia, [:Australian, :Aussie], :Peru, :Peruvian] 6 | demonyms.flatten 2 7 | #=> [:Barbados, :Bajan, :Spain, :Spaniard, :Ireland, :Irish, 8 | #=> :Australia, :Australian, :Aussie, :Peru, :Peruvian] 9 | demonyms.invert 10 | #=> {:Bajan=>:Barbados, :Spaniard=>:Spain, :Irish=>:Ireland, 11 | #=> [:Australian, :Aussie]=>:Australia, :Peruvian=>:Peru} 12 | -------------------------------------------------------------------------------- /examples/hash-values.rb: -------------------------------------------------------------------------------- 1 | snomed = {T: :Topography, M: :Morphology, L: :Living_organisms, C: :Chemical, 2 | F: :Fever, J: :Occupation, D: :Diagnosis, P: :Procedure, 3 | A: :Physical, S: :Social_context, G: :General} 4 | snomed.value? :Diagnosis #=> true 5 | snomed.value? :Imaginary #=> false 6 | snomed.values #=> [:Topography, :Morphology, :Living_organisms, :Chemical, :Fever, :Occupation, 7 | #=> :Diagnosis, :Procedure, :Physical, :Social_context, :General] 8 | snomed.each_value.reject{|v| v =~ /^#{snomed.key(v)}/} #=> [:Occupation, :Physical] 9 | -------------------------------------------------------------------------------- /examples/here-doc.rb: -------------------------------------------------------------------------------- 1 | poem = <<-POEM 2 | Me up at does 3 | 4 | out of the floor 5 | quietly Stare 6 | 7 | a poisoned mouse 8 | 9 | still who alive 10 | 11 | is asking What 12 | have i done that 13 | 14 | You wouldn't have 15 | -- Edward Estlin Cummings 16 | POEM 17 | -------------------------------------------------------------------------------- /examples/hex-byte-escape.rb: -------------------------------------------------------------------------------- 1 | "\x68\x65\x78" #=> "hex" 2 | -------------------------------------------------------------------------------- /examples/if-statement-simple.rb: -------------------------------------------------------------------------------- 1 | if true 2 | :verdadero 3 | end #=> :verdadero 4 | 5 | if false then :falso end #=> nil 6 | -------------------------------------------------------------------------------- /examples/if-statement-with-else-clause.rb: -------------------------------------------------------------------------------- 1 | if :cat > :dogs 2 | "Meow" 3 | else 4 | "Woof!" 5 | end #=> "Woof!" 6 | 7 | -------------------------------------------------------------------------------- /examples/if-statement-with-elsif-and-else-clause.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | class Integer 3 | require 'prime' 4 | 5 | def square_free? 6 | prime_division.map(&:last).all?{|p| p == 1} 7 | end 8 | 9 | def möbius 10 | return if self < 1 # Postfix if statement 11 | if not square_free? then 0 12 | elsif prime_division.map(&:first).uniq.size.odd? then -1 13 | else 1 14 | end 15 | end 16 | end 17 | (1..10).map(&:möbius) #=> [1, -1, -1, 0, -1, 1, -1, 0, 0, 1] 18 | -------------------------------------------------------------------------------- /examples/ignoring-invalid-byte-sequence.rb: -------------------------------------------------------------------------------- 1 | source, dest = "a\u6543bc", "" 2 | source.setbyte(2,0) 3 | ec = Encoding::Converter.new('utf-8', 'ascii') 4 | until source.empty? 5 | ec.primitive_convert(source, dest) 6 | p [source, dest, *ec.primitive_errinfo] 7 | end 8 | #=> ["\x83bc", "a", :invalid_byte_sequence, "UTF-8", "US-ASCII", "\xE6", "\x00"] 9 | #=> ["bc", "a\x00", :invalid_byte_sequence, "UTF-8", "US-ASCII", "\x83", ""] 10 | #=> ["", "a\x00bc", :finished, nil, nil, nil, nil] 11 | -------------------------------------------------------------------------------- /examples/implicit-receiver-for-private-method.rb: -------------------------------------------------------------------------------- 1 | class Schneier 2 | private 3 | def blowfish 4 | "Teach a man to fish..." 5 | end 6 | end 7 | Schneier.new.blowfish #=> NoMethodError 8 | 9 | class Schneier 10 | def backdoor 11 | self.blowfish 12 | end 13 | end 14 | Schneier.new.backdoor #=> NoMethodError 15 | 16 | class Schneier 17 | def backdoor 18 | blowfish 19 | end 20 | end 21 | Schneier.new.backdoor #=> "Teach a man to fish..." 22 | -------------------------------------------------------------------------------- /examples/insert-output.rb: -------------------------------------------------------------------------------- 1 | source, dest = "a\ubeefbc", "" 2 | ec = Encoding::Converter.new('utf-8', 'ascii') 3 | until source.empty? 4 | if ec.primitive_convert(source, dest) == :undefined_conversion 5 | ec.insert_output("" % ec.last_error.error_char.ord) 6 | end 7 | p [source, dest, *ec.primitive_errinfo] 8 | end 9 | #=> ["bc", "a", :undefined_conversion, "UTF-8", "US-ASCII", "\xEB\xBB\xAF", ""] 10 | #=> ["", "abc", :finished, nil, nil, nil, nil] 11 | -------------------------------------------------------------------------------- /examples/integer-downto-loop.rb: -------------------------------------------------------------------------------- 1 | 10.downto(1) do |count| 2 | print count, ' ' 3 | puts "Blast off!" if count == 1 4 | end #=> 10 5 | # 10 9 8 7 6 5 4 3 2 1 Blast off! 6 | -------------------------------------------------------------------------------- /examples/integer-times-loop.rb: -------------------------------------------------------------------------------- 1 | def times_tables n 2 | max_width = (n * n).to_s.size 3 | n.times do |x| 4 | n.times do |y| 5 | printf "%#{max_width}d ", x.succ * y.succ 6 | end 7 | puts 8 | end 9 | end 10 | times_tables 10 11 | # 1 2 3 4 5 6 7 8 9 10 12 | # 2 4 6 8 10 12 14 16 18 20 13 | # 3 6 9 12 15 18 21 24 27 30 14 | # 4 8 12 16 20 24 28 32 36 40 15 | # 5 10 15 20 25 30 35 40 45 50 16 | # 6 12 18 24 30 36 42 48 54 60 17 | # 7 14 21 28 35 42 49 56 63 70 18 | # 8 16 24 32 40 48 56 64 72 80 19 | # 9 18 27 36 45 54 63 72 81 90 20 | # 10 20 30 40 50 60 70 80 90 100 21 | -------------------------------------------------------------------------------- /examples/integer-upto-loop.rb: -------------------------------------------------------------------------------- 1 | ten_times = [] 2 | 10.upto(15) do |i| 3 | ten_times << i * 10 4 | end #=> 10 5 | ten_times #=> [100, 110, 120, 130, 140, 150] 6 | -------------------------------------------------------------------------------- /examples/invocation-semantics-break.rb: -------------------------------------------------------------------------------- 1 | hug = ->(who) do 2 | break "{#{who}}" 3 | :xxx # Not reached 4 | end 5 | name = :maria 6 | p ["Hugging #{name}", hug.call(name), "Hugged #{name}"] 7 | #=> ["Hugging maria", "{maria}", "Hugged maria"] 8 | -------------------------------------------------------------------------------- /examples/invocation-semantics-return.rb: -------------------------------------------------------------------------------- 1 | hug = ->(who) do 2 | return "{#{who}}" 3 | :xxx # Not reached 4 | end 5 | name = :jess 6 | p ["Hugging #{name}", hug.call(name), "Hugged #{name}"] 7 | #=> ["Hugging jess", "{jess}", "Hugged jess"] 8 | -------------------------------------------------------------------------------- /examples/io-close.rb: -------------------------------------------------------------------------------- 1 | $stdin.closed? #=> false 2 | $stdin.close #=> nil 3 | $stdin.gets #=> IOError 4 | pipe = IO.popen(ENV['SHELL'],'r+') 5 | pipe.close_write #=> nil 6 | pipe.closed? #=> false 7 | pipe.close_read #=> nil 8 | pipe.closed? #=> true 9 | -------------------------------------------------------------------------------- /examples/io-close_on_exec.rb: -------------------------------------------------------------------------------- 1 | open('/tmp/f','w'){|f| f << 'sekrit'} 2 | f = open('/tmp/f') 3 | f.close_on_exec? #=> false 4 | exec("ruby -e 'p IO.open(#{f.fileno}).read'") 5 | # Prints "sekrit" 6 | -------------------------------------------------------------------------------- /examples/io-close_on_exec2.rb: -------------------------------------------------------------------------------- 1 | open('/tmp/f','w'){|f| f << 'sekrit'} 2 | f = open('/tmp/f') 3 | f.close_on_exec = true 4 | f.close_on_exec? #=> true 5 | exec("ruby -e 'p IO.open(#{f.fileno}).read'") 6 | # Prints: 7 | #-e:1:in `initialize': Bad file descriptor (Errno::EBADF) 8 | # from -e:1:in `open' 9 | # from -e:1:in `
' 10 | -------------------------------------------------------------------------------- /examples/io-copy.rb: -------------------------------------------------------------------------------- 1 | File.open('/tmp/a', ?w){|f| f.puts (?a..?z).to_a.join} 2 | IO.copy_stream(File.open('/tmp/a'), '/tmp/b', 6, 2) #=> 6 3 | File.read('/tmp/b') #=> "cdefgh" 4 | -------------------------------------------------------------------------------- /examples/io-fcntl.rb: -------------------------------------------------------------------------------- 1 | require 'fcntl' 2 | $stdout.fcntl(Fcntl::F_DUPFD) #=> 3 3 | f = open('/tmp/file', ?w) 4 | f.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) 5 | f.close_on_exec? #=> true 6 | access_mode = f.fcntl(Fcntl::F_GETFL) & Fcntl::O_ACCMODE 7 | access_mode == Fcntl::O_WRONLY #=> true 8 | f.fcntl(Fcntl::F_SETFL, access_mode | Fcntl::O_APPEND) 9 | f.fcntl(Fcntl::F_GETFL) & Fcntl::O_APPEND == Fcntl::O_APPEND #=> true 10 | -------------------------------------------------------------------------------- /examples/io-ioctl.rb: -------------------------------------------------------------------------------- 1 | # Value of KDSETLED; see `man 2 ioctl_list` or `grep` /usr/include for 2 | # the corresponding value on your system 3 | KDSETLED = 0x4B32 4 | def flash n 5 | @tty ||= open("/dev/console") # You'll probably need to be root 6 | @tty.ioctl(KDSETLED, n) 7 | sleep 0.1 8 | end 9 | 10 | at_exit { flash 0 } 11 | 12 | loop do 13 | (0..6).each do |n| 14 | [n, ~n, n].each{|m| flash m } 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /examples/io-pipe.rb: -------------------------------------------------------------------------------- 1 | r, w = IO.pipe 2 | w << 'secret' 3 | w << ' message' 4 | w.close_write 5 | r.read #=> "secret message" 6 | -------------------------------------------------------------------------------- /examples/io-select.rb: -------------------------------------------------------------------------------- 1 | pipes = 5.times.map{ IO.pipe } 2 | readers, writers = pipes.map(&:first), pipes.map(&:last) 3 | Thread.new do 4 | writers.shuffle! 5 | while w = writers.pop 6 | sleep(w.to_i / writers.size) and w << "#{w.to_i}" 7 | w.close 8 | end 9 | end.run 10 | until readers.empty? do 11 | ready = select(readers, writers, [], 1) or abort "Got bored" 12 | ready.first.each do |box| 13 | begin 14 | print "#{box.readline} (wait: #{ready[1].size}) " 15 | rescue EOFError 16 | readers.delete(box) 17 | end 18 | end 19 | end 20 | # 12 (wait: 4) 10 (wait: 3) 4 (wait: 2) 8 (wait: 1) Got bored 21 | -------------------------------------------------------------------------------- /examples/kernel-binding-example.rb: -------------------------------------------------------------------------------- 1 | class Context 2 | @@where = :class 3 | def self.context 4 | binding 5 | end 6 | end 7 | eval "@@where", Context.context #=> :class 8 | -------------------------------------------------------------------------------- /examples/kernel-exec-1.rb: -------------------------------------------------------------------------------- 1 | exec("no-such-command") 2 | #=> Errno::ENOENT 3 | exec("ls /usr/share/dict/* | wc") 4 | # 5 5 172 5 | -------------------------------------------------------------------------------- /examples/kernel-exec-2.rb: -------------------------------------------------------------------------------- 1 | exec("uname", "-s") 2 | # Linux 3 | -------------------------------------------------------------------------------- /examples/kernel-exec-3.rb: -------------------------------------------------------------------------------- 1 | script = "/tmp/script.rb" 2 | open(script, ?w){|f| f << "#!/usr/local/bin/ruby\np ENV['GLARK']"} 3 | File.chmod 0755, script 4 | exec({'GLARK' => 'always'}, script) 5 | # Prints "always" 6 | -------------------------------------------------------------------------------- /examples/kernel-fork-2.rb: -------------------------------------------------------------------------------- 1 | print "\nIn #{(pid = fork) ? "parent (#{pid})" : "child (#{Process.pid})"}: " 2 | 2.times{|i| print "#{i} "} 3 | # Prints: 4 | # 5 | # In parent (24225): 0 1 6 | # In child (24225): 0 1 7 | -------------------------------------------------------------------------------- /examples/kernel-fork.rb: -------------------------------------------------------------------------------- 1 | puts "Parent: #{Process.ppid} -> #{Process.pid}" 2 | fork do 3 | puts "Child: #{Process.ppid} -> #{Process.pid}" 4 | end 5 | 6 | # Prints: 7 | # Parent: 6653 -> 16743 8 | # Child: 16743 -> 16745 9 | -------------------------------------------------------------------------------- /examples/kernel-open-opts.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | open('/tmp/file', mode: ?w) {|f| f.print "text\r\n"} 3 | text = File.read('/tmp/file') #=> "text\r\n" 4 | text.encoding == Encoding::UTF_8 5 | open('/tmp/file', mode: ?a){|f| f << "more text"} 6 | open('/tmp/file', textmode: true, external_encoding: 'ascii') do |f| 7 | text = f.read #=> "text\nmore text" 8 | text.encoding #=> Encoding::US_ASCII 9 | end 10 | -------------------------------------------------------------------------------- /examples/kernel-rand.rb: -------------------------------------------------------------------------------- 1 | srand 0xDEAF #=> 158965985081249152526188226346818216914 2 | rand #=> 0.9812733995904889 3 | rand 30 #=> 1 4 | rand -45 #=> 25 5 | rand Math::PI #=> 2 6 | -------------------------------------------------------------------------------- /examples/kernel-spawn.rb: -------------------------------------------------------------------------------- 1 | pid = spawn('cat /dev/urandom > /dev/null') #=> 24206 2 | `ps --no-headers #{pid}` 3 | #=> "24206 pts/1 S+ 0:00 sh -c cat /dev/urandom > /dev/null\n" 4 | system("kill #{pid}") #=> true 5 | -------------------------------------------------------------------------------- /examples/kernel-system.rb: -------------------------------------------------------------------------------- 1 | system('git init') #=> true 2 | system(*%w{gpg -r runrun@runpaint.org --encrypt file}) #=> true 3 | system("cat glark") #=> false 4 | # cat: glark: No such file or directory 5 | system("xzxzxzxz") #=> nil 6 | -------------------------------------------------------------------------------- /examples/lambda-keyword-examples.rb: -------------------------------------------------------------------------------- 1 | def intermittently wait, closure 2 | loop { sleep(wait.call) and rv = closure[Time.now] and return rv } 3 | end 4 | require 'prime' 5 | prime_time = lambda do |t| 6 | t.strftime("%T:%6N") if [t.hour, t.min, t.sec, t.usec].all?(&:prime?) 7 | end 8 | intermittently lambda { Random.new.rand(3.0) }, prime_time #=> "11:29:47:435997" 9 | -------------------------------------------------------------------------------- /examples/lambda-literal-syntax.rb: -------------------------------------------------------------------------------- 1 | require 'resolv' 2 | ->(host) do 3 | Resolv.getaddress host 4 | end.call 'runpaint.org' #=> "208.94.116.80" 5 | resolv = ->(ips) { Hash[ ips.map {|ip| [ip, Resolv.getname(ip)]} ] } 6 | resolv[%w{128.9.160.27 66.80.146.7 65.181.149.201 217.147.82.116}] 7 | #=> {"128.9.160.27" =>"www.rfc-editor.org", "66.80.146.7" =>"forced.attrition.org", 8 | #=> "65.181.149.201"=>"ycombinator.com", "217.147.82.116"=>"ns.irational.org"} 9 | resolv.('128.30.52.45', '69.13.187.182') 10 | #=> in `call': wrong number of arguments (2 for 1) (ArgumentError) 11 | -------------------------------------------------------------------------------- /examples/lazy-quantifiers.rb: -------------------------------------------------------------------------------- 1 | str = 'indolent poltroon!' 2 | str.match /ro?/ #=> # 3 | str.match /ro??/ #=> # 4 | str.match /n*t/ #=> # 5 | str.match /n*?t/ #=> # 6 | str.match /i.+t/ #=> # 7 | str.gsub(/i.+?t/, 'gluttonous') #=> "gluttonous poltroon!" 8 | -------------------------------------------------------------------------------- /examples/left-shift-selector.rb: -------------------------------------------------------------------------------- 1 | 4 << 64 #=> 73786976294838206464 2 | '4' << 64 #=> "4@" 3 | [4] << 64 #=> [4, 64] 4 | -------------------------------------------------------------------------------- /examples/less-than-selector.rb: -------------------------------------------------------------------------------- 1 | 42 < 43 #=> true 2 | 10 < 1 #=> false 3 | 'a' < 'aa' #=> true 4 | 'z' < 'Z' #=> false 5 | -------------------------------------------------------------------------------- /examples/load.rb: -------------------------------------------------------------------------------- 1 | load './a.rb' #=> true 2 | @ivar #=> :i 3 | @ivar = :j 4 | load './a.rb' #=> true 5 | @ivar #=> :i 6 | -------------------------------------------------------------------------------- /examples/local-variables-assignment.rb: -------------------------------------------------------------------------------- 1 | if false 2 | glark = 2 3 | end 4 | defined? glark #=> 'local-variable' 5 | glark #=> nil 6 | -------------------------------------------------------------------------------- /examples/local-variables-uninitialized.rb: -------------------------------------------------------------------------------- 1 | var #=> NameError: undefined local variable or method `var' for main:Object 2 | -------------------------------------------------------------------------------- /examples/local-variables.rb: -------------------------------------------------------------------------------- 1 | def scope 2 | variable = 1 3 | 3.times do 4 | variable += 1 5 | end 6 | variable 7 | end 8 | scope #=> 4 9 | defined? variable #=> nil 10 | -------------------------------------------------------------------------------- /examples/loop-loop-fig.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def happy? 3 | return false unless self > 0 4 | sad, sequence = [4, 16, 37, 58, 89, 145, 42, 20], [self] 5 | loop do 6 | sequence << sequence.last.to_s.split(//).map{|d| d.to_i ** 2}.reduce(:+) 7 | return true if sequence.last == 1 8 | return false if sequence.last(sad.size) == sad 9 | end 10 | end 11 | end 12 | (1..15).select(&:happy?) #=> [1, 7, 10, 13] 13 | -------------------------------------------------------------------------------- /examples/math-log.rb: -------------------------------------------------------------------------------- 1 | include Math 2 | log E**7 #=> 7.0 3 | log 81, 9 #=> 2.0 4 | log10 10_000_000_000_000 #=> 13.0 5 | log10 Float::RADIX**Float::MANT_DIG #=> 15.954589770191003 6 | log2 Rational(1024, 16) #=> 6.0 7 | -------------------------------------------------------------------------------- /examples/message-chaining-inconsistent-return-value.rb: -------------------------------------------------------------------------------- 1 | " All propositions are of equal value. ".strip!.sub(/\.$/,'!') 2 | #=> "All propositions are of equal value!" 3 | "All propositions are of equal value.".strip!.sub(/\.$/,'!') 4 | #=> NoMethodError: undefined method `sub' for nil:NilClass 5 | -------------------------------------------------------------------------------- /examples/message-chaining-return-self.rb: -------------------------------------------------------------------------------- 1 | " All propositions are of equal value. ".strip.sub(/\.$/,'!') 2 | #=> "All propositions are of equal value!" 3 | "All propositions are of equal value.".strip.sub(/\.$/,'!') 4 | #=> "All propositions are of equal value!" 5 | -------------------------------------------------------------------------------- /examples/message-chaining.rb: -------------------------------------------------------------------------------- 1 | (100..110).map{|n| n / 5 } 2 | #=> [20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 22] 3 | (100..110).map{|n| n / 5 }.uniq #=> [20, 21, 22] 4 | (100..110).map{|n| n / 5 }.uniq.first(2) #=> [20, 21] 5 | (100..110).map{|n| n / 5 }.uniq.first(2).reduce(:+) #=> 41 6 | -------------------------------------------------------------------------------- /examples/message-expression-with-block.rb: -------------------------------------------------------------------------------- 1 | 3.times {|number| print number ** 2, ', ' } #=> 3 2 | # 0, 1, 4, 3 | 4 | (:a..:z).select do |letter| 5 | letter > :r && letter < :y 6 | end #=> [:s, :t, :u, :v, :w, :x] 7 | -------------------------------------------------------------------------------- /examples/message-expressions-omit-parentheses-syntaxerror.rb: -------------------------------------------------------------------------------- 1 | cubes = [1.0] 2 | cubes.push cubes.first * 8, Math.log2 134217728, 64.0 3 | #=> SyntaxError: syntax error, unexpected tINTEGER, expecting $end 4 | # cubes.push cubes.first * 8, Math.log2 134217728, 64.0 5 | # ^ 6 | cubes.push cubes.first * 8, Math.log2(134217728), 64.0 7 | #=> [1.0, 8.0, 27.0, 64.0] 8 | -------------------------------------------------------------------------------- /examples/meta-escape.rb: -------------------------------------------------------------------------------- 1 | "\M-y".ord #=> 249 2 | "\M-\C-B".ord #=> 130 3 | -------------------------------------------------------------------------------- /examples/method-defined.rb: -------------------------------------------------------------------------------- 1 | String.instance_methods.include?(:try_convert) #=> false 2 | String.method_defined?(:try_convert) #=> false 3 | String.singleton_methods.include?(:try_convert) #=> true 4 | String.respond_to?(:try_convert) #=> true 5 | 6 | String.instance_methods.include?(:upcase) #=> true 7 | String.method_defined?(:upcase) #=> true 8 | String.singleton_methods.include?(:upcase) #=> false 9 | String.respond_to?(:upcase) #=> false 10 | -------------------------------------------------------------------------------- /examples/method-invocation-with-block-literal.rb: -------------------------------------------------------------------------------- 1 | def m 2 | :m 3 | end 4 | m { 1 + 2 } 5 | m do 6 | 1 + 2 7 | end 8 | -------------------------------------------------------------------------------- /examples/method-lookup.rb: -------------------------------------------------------------------------------- 1 | class Parent 2 | def method 3 | :superclass_instance # 4 4 | end 5 | end 6 | module M 7 | def method 8 | :module_instance # 3 9 | end 10 | end 11 | class C < Parent 12 | include M 13 | def method 14 | :class_instance # 2 15 | end 16 | end 17 | 18 | object = C.new 19 | def object.method 20 | :object_singleton # 1 21 | end 22 | -------------------------------------------------------------------------------- /examples/method-receiving-block-ref.rb: -------------------------------------------------------------------------------- 1 | def m(b) 2 | b.call 3 | end 4 | m ->{ "I am a \u{3bb}!" } #=> "I am a λ!" 5 | -------------------------------------------------------------------------------- /examples/method-using-block-argument.rb: -------------------------------------------------------------------------------- 1 | def m(&block) 2 | puts "This block returns: #{block.call}" if block_given? 3 | end 4 | m { 1 + 2 } #=> This block returns: 3 5 | m #=> nil 6 | -------------------------------------------------------------------------------- /examples/method-using-block-given-yield.rb: -------------------------------------------------------------------------------- 1 | def m 2 | puts "This block returns: #{yield}" if block_given? 3 | end 4 | m { 1 + 2 } #=> This block returns: 3 5 | m #=> nil 6 | -------------------------------------------------------------------------------- /examples/method-using-block-given.rb: -------------------------------------------------------------------------------- 1 | def m 2 | puts "Thanks" if block_given? 3 | end 4 | m { 1 + 2 } #=> "Thanks" 5 | m #=> nil 6 | -------------------------------------------------------------------------------- /examples/module-attr-accessor.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | class King 3 | @numeral = Hash.new {|h,k| h[k] = 8543.chr('utf-8') } 4 | singleton_class.class_eval{ attr_accessor :numeral } 5 | 6 | def initialize(name) 7 | King.numeral[@name = name].succ! 8 | end 9 | 10 | def name 11 | "#@name #{King.numeral[@name]}".sub(/ Ⅰ$/, '') 12 | end 13 | end 14 | %w{Henry Stephen Henry Richard John Henry Edward Edward 15 | Edward Richard Henry}.map {|name| King.new(name).name}.join(', ') 16 | #=> Henry, Stephen, Henry Ⅱ, Richard, John, Henry Ⅲ, Edward, 17 | # Edward Ⅱ, Edward Ⅲ, Richard Ⅱ, Henry Ⅳ 18 | -------------------------------------------------------------------------------- /examples/module-function-extend-self.rb: -------------------------------------------------------------------------------- 1 | module ISBN 2 | extend self 3 | # Convert ISBN-13 to ISBN-10 4 | def thirteen_to_ten(isbn) 5 | csum = checksum10(isbn = isbn.to_s[3,9]) 6 | isbn + ({10 => 'X', 11 => '0'}[csum] || csum.to_s) 7 | end 8 | 9 | private 10 | def checksum10(isbn, weight=11) 11 | 11 - isbn.chars.reduce(0){|mem,c| mem + (c.to_i * weight -= 1)} % 11 12 | end 13 | end 14 | 15 | isbns = {'9780596529260' => '0596529260', 16 | '9780596102432' => '0596102437', 17 | '9780596007591' => '0596007590'} 18 | isbns.all?{|thirteen, ten| ISBN.thirteen_to_ten(thirteen) == ten} #=> true 19 | include ISBN 20 | isbns.all?{|thirteen, ten| thirteen_to_ten(thirteen) == ten} #=> true 21 | -------------------------------------------------------------------------------- /examples/module-function-private-method.rb: -------------------------------------------------------------------------------- 1 | module ISBN 2 | module_function 3 | # Convert ISBN-13 to ISBN-10 4 | def thirteen_to_ten(isbn) 5 | csum = checksum10(isbn = isbn.to_s[3,9]) 6 | isbn + ({10 => 'X', 11 => '0'}[csum] || csum.to_s) 7 | end 8 | 9 | private 10 | def checksum10(isbn, weight=11) 11 | 11 - isbn.chars.reduce(0){|mem,c| mem + (c.to_i * weight -= 1)} % 11 12 | end 13 | end 14 | 15 | isbns = {'9780596529260' => '0596529260', 16 | '9780596102432' => '0596102437', 17 | '9780596007591' => '0596007590'} 18 | isbns.all?{|thirteen, ten| ISBN.thirteen_to_ten(thirteen) == ten} 19 | #=> `thirteen_to_ten': undefined method `checksum10' for ISBN:Module (NoMethodError) 20 | -------------------------------------------------------------------------------- /examples/module-function.rb: -------------------------------------------------------------------------------- 1 | module ISBN 2 | module_function 3 | # Convert ISBN-13 to ISBN-10 4 | def thirteen_to_ten(isbn) 5 | isbn, weight = isbn.to_s[3,9].chars, 11 6 | csum = 11 - isbn.reduce(0){|mem,c| mem + (c.to_i * weight -= 1)} % 11 7 | isbn.join + ({10 => 'X', 11 => '0'}[csum] || csum.to_s) 8 | end 9 | end 10 | 11 | isbns = {'9780596529260' => '0596529260', 12 | '9780596102432' => '0596102437', 13 | '9780596007591' => '0596007590'} 14 | isbns.all?{|thirteen, ten| ISBN.thirteen_to_ten(thirteen) == ten} #=> true 15 | include ISBN 16 | isbns.all?{|thirteen, ten| thirteen_to_ten(thirteen) == ten} #=> true 17 | -------------------------------------------------------------------------------- /examples/module-namespace-and-mixin.rb: -------------------------------------------------------------------------------- 1 | Math.cbrt 33 #=> 3.2075343299958265 2 | include Math 3 | cbrt 3 #=> 1.4422495703074085 4 | -------------------------------------------------------------------------------- /examples/module-namespacing-extend-self.rb: -------------------------------------------------------------------------------- 1 | module CPU 2 | extend self 3 | def processors 4 | File.read('/proc/cpuinfo').split(/\n\n/).map{|processor| Hash[ 5 | processor.lines.reject{|line| line.end_with?(':')}. 6 | map{|line| normalise *line.chomp.split(/\t+:\s?/)} 7 | ]} 8 | end 9 | 10 | private 11 | def normalise(key, value) 12 | key = key.gsub(/\s/,'_').to_sym 13 | return [key, value.split.map(&:to_sym)] if key == :flags 14 | [key] << case value 15 | when /^\d+$/ then value.to_i 16 | when /^\d+\.\d+$/ then value.to_f 17 | when 'no' then false 18 | when 'yes' then true 19 | else value 20 | end 21 | end 22 | end 23 | 24 | cpu = CPU.processors.first 25 | cpu[:model_name] + ' has the :mmx flag set' if cpu[:flags].include?(:mmx) 26 | #=> "Intel(R) Atom(TM) CPU N270 @ 1.60GHz has the :mmx flag set" 27 | "It doesn't have any known bugs" if cpu.keys.grep(/_bug/).map{|bug| cpu[bug]}.none? 28 | #=> "It doesn't have any known bugs" 29 | "Its faster than 500MHz" if cpu[:cpu_MHz] > 500 30 | #=> "Its faster than 500MHz" 31 | -------------------------------------------------------------------------------- /examples/module-namespacing.rb: -------------------------------------------------------------------------------- 1 | module CPU 2 | def self.processors 3 | File.read('/proc/cpuinfo').split(/\n\n/).map{|processor| Hash[ 4 | processor.lines.reject{|line| line.end_with?(':')}. 5 | map{|line| line.chomp.split(/\t+:\s?/)} 6 | ]} 7 | end 8 | end 9 | 10 | cpu = CPU.processors.first 11 | cpu['model name'] + ' with a ' + cpu['cache size'] + ' cache' 12 | #=> "Intel(R) Atom(TM) CPU N270 @ 1.60GHz with a 512 KB cache" 13 | -------------------------------------------------------------------------------- /examples/module-new.rb: -------------------------------------------------------------------------------- 1 | indeterminate = Module.new do 2 | def size 3 | end 4 | end 5 | indeterminate.name #=> nil 6 | quantities = [3, 7, 11, 47] 7 | quantities.extend(indeterminate) 8 | quantities.size #=> nil 9 | Indeterminate = indeterminate 10 | indeterminate.name #=> "Indeterminate" 11 | -------------------------------------------------------------------------------- /examples/named-arguments-with-defaults.rb: -------------------------------------------------------------------------------- 1 | class Chair 2 | DEFAULT_ARGS = {legs: 2, style: :victorian, height: :average, colour: :brown} 3 | def initialize(args) 4 | @attributes = DEFAULT_ARGS.merge args 5 | end 6 | end 7 | Chair.new legs: 4, height: :tall #=> 8 | #4, :style=>:victorian, 10 | #:height=>:tall, :colour=>:brown 11 | #};> 12 | Chair.new(:color => :fuschia, :legs => 7) #=> 13 | ##7, :style=>:victorian, 15 | #:height=>:average, :colour=>:fuschia 16 | #}>; 17 | -------------------------------------------------------------------------------- /examples/named-arguments-with-hash.rb: -------------------------------------------------------------------------------- 1 | class Chair 2 | def initialize(args) 3 | @legs = args[:legs] or raise ArgumentError 4 | @style = args[:style] || :victorian 5 | @height = args[:height] || :average 6 | @colour = args[:colour] || args[:color] || :brown 7 | end 8 | end 9 | Chair.new legs: 4, height: :tall 10 | #=> # 12 | Chair.new(:color => :fuschia, :legs => 7) 13 | #=> # 15 | Chair.new(height: :childs, color: :fuschia) 16 | #=> ArgumentError 17 | -------------------------------------------------------------------------------- /examples/next.rb: -------------------------------------------------------------------------------- 1 | ips = Hash.new {|h,k| h[k] = []} 2 | IO.foreach('/etc/hosts').each do |line| 3 | next if line.start_with?('#') 4 | ip, *hosts = line.split 5 | ips[ip] += hosts 6 | end 7 | ips #=> {"127.0.0.1"=>["localhost"], "127.0.1.1"=>["paint", "read-ruby"], 8 | # "::1"=>["localhost"]} #... 9 | 10 | -------------------------------------------------------------------------------- /examples/nil-guard.rb: -------------------------------------------------------------------------------- 1 | var ||= Time.now 2 | var #=> 2010-02-19 10:51:07 +0000 3 | var ||= Time.now 4 | var #=> 2010-02-19 10:51:07 +0000 5 | -------------------------------------------------------------------------------- /examples/non-block-local-variables-clo.rb: -------------------------------------------------------------------------------- 1 | non-block-local-variables.rb -------------------------------------------------------------------------------- /examples/non-block-local-variables.rb: -------------------------------------------------------------------------------- 1 | v = :out 2 | 1.times do 3 | v, w = :in, :in 4 | p [v, w] 5 | end #=> [:in, :in] 6 | v #=> :in 7 | w #=> NameError 8 | -------------------------------------------------------------------------------- /examples/not-operator-fig.rb: -------------------------------------------------------------------------------- 1 | not true #=> false 2 | not not nil #=> false 3 | !!:false #=> true 4 | 3 > 2 and !3.even? and not 3.zero? #=> true 5 | -------------------------------------------------------------------------------- /examples/numeric-bases.rb: -------------------------------------------------------------------------------- 1 | 67.to_s 2 #=> "1000011" 2 | 134.to_s 16 #=> "86" 3 | 98765.to_s 30 #=> "3jm5" 4 | '10111011101'.to_i 2 #=> 1501 5 | 'beef'.hex #=> 48879 6 | '%#X' % 36617 #=> "0X8F09" 7 | -------------------------------------------------------------------------------- /examples/numeric-bits.rb: -------------------------------------------------------------------------------- 1 | def next_power_of_2 n 2 | [1,2,4,8,16].inject(n - 1){|memo, x| memo |= memo >> x}.succ 3 | end 4 | [34, 67, 82720, 1024].map{|n| next_power_of_2 n} #=> [64, 128, 131072, 1024] 5 | 6 | mask =->(pos) { 1 << pos } 7 | set_bit =->(f, pos) { f | mask[pos]} 8 | clear_bit =->(f, pos) { f & ~(mask[pos])} 9 | modify_bit =->(f, pos, state){ f & ~mask[pos] | (-state & mask[pos])} 10 | f = 0b1110001 11 | f = set_bit[f, 3]; f.to_s(2) #=> "1111001" 12 | f = clear_bit[f, 5]; f.to_s(2) #=> "1011001" 13 | f = modify_bit[f, 0, 0]; f.to_s(2) #=> "1011000" 14 | -------------------------------------------------------------------------------- /examples/numeric-coerce.rb: -------------------------------------------------------------------------------- 1 | 23.coerce 567 #=> [567, 23] 2 | 23.coerce 5.67 #=> [5.67, 23.0] 3 | Math::PI.coerce Rational(1, 2) #=> [0.5, 3.141592653589793] 4 | Complex(2).coerce Float::INFINITY #=> [(Infinity+0i), (2+0i)] 5 | -------------------------------------------------------------------------------- /examples/numeric-division.rb: -------------------------------------------------------------------------------- 1 | 5 / 2 #=> 2 2 | 5.fdiv 2 #=> 2.5 3 | 5.quo 2 #=> (5/2) 4 | 33.quo 3.3 #=> 10.0 5 | Rational(100, 3) / 0.3 #=> 111.11111111111113 6 | Rational(100, 3) / 3 #=> (100/9) 7 | -------------------------------------------------------------------------------- /examples/numeric-equal-coerce.rb: -------------------------------------------------------------------------------- 1 | 3 == 3.0 #=> true 2 | a, b = 3.coerce(3.0) #=> [3.0, 3.0] 3 | a.eql? b #=> true 4 | 5 | Rational(2, 3) == 2.3 #=> false 6 | a, b = Rational(2, 3).coerce(2.3) #=> [2.3, 0.6666666666666666] 7 | a.eql? b #=> false 8 | -------------------------------------------------------------------------------- /examples/numeric-equality.rb: -------------------------------------------------------------------------------- 1 | 23 == 23 2 | 10 != 10.00000000000001 3 | 34 != -34 4 | Rational(56, 64) == Rational(7, 8) 5 | Rational(3, 4) == 0.75 6 | Complex(3) == Rational(3) 7 | Complex(2, 10) != Rational(2, 10) 8 | Rational(Rational(16.0, 1), Complex(8)) == 2 9 | -------------------------------------------------------------------------------- /examples/numeric-inequality.rb: -------------------------------------------------------------------------------- 1 | 34 < 43 2 | 109 >= 100.9 3 | Rational(7,5) > Rational(1, 5) 4 | p ((2**781) < Float::INFINITY) #http://redmine.ruby-lang.org/issues/show/3648 5 | Float::NAN != Float::NAN 6 | -------------------------------------------------------------------------------- /examples/numeric-modulo.rb: -------------------------------------------------------------------------------- 1 | 5 % 10 #=> 5 2 | 15 % 10 #=> 5 3 | (-2..6).map{|n| n % 4} #=> [2, 3, 0, 1, 2, 3, 0, 1, 2] 4 | -------------------------------------------------------------------------------- /examples/numeric-predicates.rb: -------------------------------------------------------------------------------- 1 | 78690.even? #=> true 2 | -23.5.finite? #=> true 3 | (-Float::INFINITY).finite? #=> false 4 | (1/0.0).infinite? #=> 1 5 | (23**7658).integer? #=> true 6 | (0/0.0).nan? #=> true 7 | (45789 * 0).nonzero? #=> nil 8 | 33.odd? #=> true 9 | Rational(1, 2).real? #=> true 10 | Complex(Rational(1, 2)).real? #=> false 11 | (0.005 * 0.004).zero? #=> false 12 | -------------------------------------------------------------------------------- /examples/numerics-rounding.rb: -------------------------------------------------------------------------------- 1 | n, r = 12345.67890, Rational(20, 7) 2 | n.truncate #=> 12345 3 | n.floor #=> 12345 4 | n.ceil #=> 12346 5 | n.round(2) #=> 12345.68 6 | n.round(-3) #=> 12000 7 | r.truncate #=> 2 8 | r.ceil #=> 3 9 | r.round 3 #=> (2857/1000) 10 | -------------------------------------------------------------------------------- /examples/object-display.rb: -------------------------------------------------------------------------------- 1 | [3, 2, 1].display 2 | # Writes "[3, 2, 1]" to $stdout 3 | 9_000.display($stderr) 4 | # Writes "9000" to $stderr 5 | -------------------------------------------------------------------------------- /examples/object-methods.rb: -------------------------------------------------------------------------------- 1 | Object.new.methods.grep /^[[:alpha:]]+\?/ 2 | #=> [:nil?, :eql?, :tainted?, :untrusted?, :frozen?, :equal?] 3 | [].methods.grep /!/ 4 | #=> [:reverse!, :rotate!, :sort!, :sort_by!, :collect!, :map!, 5 | # :select!, :reject!, :slice!, :uniq!, :compact!, :flatten!, 6 | # :shuffle!, :!~, :!, :!=] 7 | String.methods false #=> [:try_convert] 8 | private_methods.grep /[[:upper:]]/ 9 | #=> [:Integer, :Float, :String, :Array, :Rational, :Complex] 10 | Object.new.tap{|o| o.define_singleton_method(:s, ->{})}.methods(false) 11 | #=> [:s] 12 | -------------------------------------------------------------------------------- /examples/object-p.rb: -------------------------------------------------------------------------------- 1 | killed_by = { 2 | 'Augustus' => nil, 3 | 'Tiberius' => nil , 4 | 'Caligula' => {who: 'Praetorian Guard'}, 5 | 'Claudius' => {who: 'wife'}, 6 | 'Nero' => {who: 'himself'} 7 | } 8 | killed_by['Nero'][:who] = killed_by['Nero'] 9 | p killed_by.select{|*, killer| killer} 10 | # Writes to $stdout: 11 | # {"Caligula"=>{:who=>"Praetorian Guard"}, "Claudius"=>{:who=>"wife"}, "Nero"=>{:who=>{...}}} 12 | -------------------------------------------------------------------------------- /examples/object-send-p.rb: -------------------------------------------------------------------------------- 1 | class Object 2 | def send?(selector, *args, &block) 3 | begin 4 | send(selector, *args, &block) 5 | rescue NoMethodError 6 | end 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /examples/object-send.rb: -------------------------------------------------------------------------------- 1 | name = :size 2 | "wool".name 3 | #=> NoMethodError: undefined method `name' for "wool":String 4 | "wool".send(name) #=> 4 5 | 33.send(:/, 3) #=> 11 6 | 7 | -------------------------------------------------------------------------------- /examples/object-try.rb: -------------------------------------------------------------------------------- 1 | class Object 2 | alias_method :try, :__send__ 3 | end 4 | 5 | class NilClass 6 | def try(*args) 7 | nil 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /examples/octal-byte-escape.rb: -------------------------------------------------------------------------------- 1 | "\157\143\164\141\154" #=> "octal" 2 | -------------------------------------------------------------------------------- /examples/optional-arguments.rb: -------------------------------------------------------------------------------- 1 | class Llama 2 | def name(name='Larry') 3 | name + ' the llama (beast of burden)' 4 | end 5 | end 6 | Llama.new.name 7 | #=> "Larry the llama (beast of burden)" 8 | Llama.new.name('Lyle Jr.') 9 | #=> "Lyle Jr. the llama (beast of burden)" 10 | Llama.new.name('Lama', 'glama') 11 | #=> ArgumentError: wrong number of arguments (2 for 1) 12 | -------------------------------------------------------------------------------- /examples/or-operator-fig.rb: -------------------------------------------------------------------------------- 1 | def valid_isbn13?(isbn) 2 | isbn = isbn.to_s.scan(/\d/).map(&:to_i) 3 | isbn.size == 13 or return false 4 | check_digit = 10 - isbn. 5 | first(12). 6 | map. 7 | with_index{|d,i| i.succ.odd? ? d : 3*d}. 8 | reduce(:+). 9 | modulo(10) 10 | (check_digit == isbn.last) or (check_digit == 10 and isbn.last.zero?) 11 | end 12 | 13 | valid_isbn13?('978-0-596-80948-5') #=> true 14 | valid_isbn13?('9780596809484') #=> false 15 | -------------------------------------------------------------------------------- /examples/parallel-assignment-equal.rb: -------------------------------------------------------------------------------- 1 | a, b, c = 1, 2, 3 2 | a #=> 1 3 | b #=> 2 4 | c #=> 3 5 | 6 | a, b = b, a 7 | a #=> 2 8 | a #=> 1 9 | -------------------------------------------------------------------------------- /examples/parallel-assignment-more-lvalues.rb: -------------------------------------------------------------------------------- 1 | a, b = 1 2 | a #=> 1 3 | b #=> nil 4 | a, b, c = :a, :b 5 | a #=> :a 6 | b #=> :b 7 | c #=> nil 8 | -------------------------------------------------------------------------------- /examples/parallel-assignment-more-rvalues.rb: -------------------------------------------------------------------------------- 1 | a, b = :a, :b, :c 2 | a #=> :a 3 | b #=> :b 4 | -------------------------------------------------------------------------------- /examples/parallel-assignment-one-lvalue.rb: -------------------------------------------------------------------------------- 1 | a = 1, 2, 3 2 | a #=> [1, 2, 3] 3 | colour, = :red, :green, :blue 4 | colour #=> :red 5 | -------------------------------------------------------------------------------- /examples/parallel-assignment-one-rvalue-nil.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | one, two = [:ūnus, :duo, :trēs] 3 | one #=> :ūnus 4 | two #=> :duo 5 | -------------------------------------------------------------------------------- /examples/parallel-assignment-one-rvalue-non-array.rb: -------------------------------------------------------------------------------- 1 | x, y = 47 2 | x #=> 47 3 | y #=> nil 4 | -------------------------------------------------------------------------------- /examples/parallel-assignment-one-rvalue.rb: -------------------------------------------------------------------------------- 1 | a, b, c = [1, 2, 3] 2 | a #=> 1 3 | b #=> 2 4 | c #=> 3 5 | -------------------------------------------------------------------------------- /examples/parallel-assignment-rvalue-to-ary.rb: -------------------------------------------------------------------------------- 1 | rvalue = Object.new 2 | def rvalue.to_ary 3 | [:alpha, :beta] 4 | end 5 | a, b = rvalue 6 | a #=> :alpha 7 | b #=> :beta 8 | -------------------------------------------------------------------------------- /examples/parallel-assignment-value.rb: -------------------------------------------------------------------------------- 1 | a, b, c = 1.5 #=> 1.5 2 | (a, b), c = 1, *[2, 3] #=> [1, 2, 3] 3 | -------------------------------------------------------------------------------- /examples/parentheses-disambiguate-bare-identifiers.rb: -------------------------------------------------------------------------------- 1 | def ambig 2 | :uous 3 | end 4 | ambig #=> :uous 5 | ambig() #=> :uous 6 | ambig = :uity 7 | ambig #=> :uity 8 | ambig() #=> :uous 9 | -------------------------------------------------------------------------------- /examples/parentheses-omitted-in-message-expressions.rb: -------------------------------------------------------------------------------- 1 | "spending".sub(/spend/, 'sav') #=> "saving" 2 | "spending".sub /spend/, 'sav' #=> "saving" 3 | ";".gsub(/(.)/, '.' => 'full stop', ',' => 'comma', 4 | ';' => 'semicolon') #=> "semicolon" 5 | ";".gsub /(.)/, '.' => 'full stop', ',' => 'comma', 6 | ';' => 'semicolon' #=> "semicolon" 7 | -------------------------------------------------------------------------------- /examples/pass-by-reference-dup.rb: -------------------------------------------------------------------------------- 1 | def llama_sans_l(llama) 2 | llama.dup.gsub!(/l/i,'') 3 | end 4 | llama = 'Larry' 5 | llama_sans_l(llama) #=> 'arry' 6 | llama #=> 'Larry' 7 | -------------------------------------------------------------------------------- /examples/pass-by-reference.rb: -------------------------------------------------------------------------------- 1 | def llama_sans_l(llama) 2 | llama.gsub!(/l/i,'') 3 | end 4 | llama = 'Larry' 5 | llama_sans_l(llama) #=> 'arry' 6 | llama #=> 'arry' 7 | -------------------------------------------------------------------------------- /examples/plural-selector-splat.rb: -------------------------------------------------------------------------------- 1 | [*'Ruby'.bytes] #=> [82, 117, 98, 121] 2 | -------------------------------------------------------------------------------- /examples/plus-selector.rb: -------------------------------------------------------------------------------- 1 | 4 + 64 #=> 68 2 | '4' + '64' #=> "464" 3 | [4] + [64] #=> [4, 64] 4 | -------------------------------------------------------------------------------- /examples/postfix-if-statement.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | balance = 250 3 | puts "You owe £#{balance}" if balance > 0 #=> "You owe £250" 4 | -------------------------------------------------------------------------------- /examples/postfix-rescue-statement.rb: -------------------------------------------------------------------------------- 1 | [2, 0].map{|denominator| 1/denominator rescue nil} 2 | #=> [0, nil] 3 | 4 | -------------------------------------------------------------------------------- /examples/postfix-unless-statement-fig.rb: -------------------------------------------------------------------------------- 1 | def palindrome?(string) 2 | raise ArgumentError unless string = String.try_convert(string) 3 | string = string.scan(/\w/).join.downcase 4 | string == string.reverse 5 | end 6 | 7 | palindrome?("Go hang a salami I'm a lasagna hog.") #=> true 8 | palindrome?("Level, madam, level!") #=> true 9 | palindrome?("canon a 2 cancrizans") #=> false 10 | palindrome?(['mad']) #=> ArgumentError 11 | -------------------------------------------------------------------------------- /examples/postfix-until-statement-fig.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | require 'prime' 3 | def next_prime 4 | n = succ 5 | n += 1 until n.prime? 6 | n 7 | end 8 | end 9 | 1.upto(10).map {|n| {n => n.next_prime}} 10 | #=> [{1=>2}, {2=>3}, {3=>5}, {4=>5}, {5=>7}, 11 | # {6=>7}, {7=>11}, {8=>11}, {9=>11}, {10=>11}] 12 | -------------------------------------------------------------------------------- /examples/postfix-while-statement-fig.rb: -------------------------------------------------------------------------------- 1 | # (n.to_s(2).count('1') works just as well, of course) 2 | def bits_set(n) 3 | bits_set = 0 4 | n &= n - 1 while n > 0 && bits_set += 1 5 | bits_set 6 | end 7 | [33, 736, 128].map{|n| bits_set(n)} #=> [2, 4, 1] 8 | -------------------------------------------------------------------------------- /examples/precedence-associativity.rb: -------------------------------------------------------------------------------- 1 | 10 - 9 - 8 #=> -7 2 | 10 - (9 - 8) #=> 9 3 | -------------------------------------------------------------------------------- /examples/precedence-parentheses.rb: -------------------------------------------------------------------------------- 1 | 4 * 3 + 1 ** 2 #=> 13 2 | 4 * (3 + 1) ** 2 #=> 64 3 | (4 * (3 + 1)) ** 2 #=> 256 4 | -------------------------------------------------------------------------------- /examples/predicate-messages.rb: -------------------------------------------------------------------------------- 1 | 33.odd? #=> true 2 | ('a'..'z').include? 'd' #=> true 3 | File.exists?(File.expand_path '~/.emacs') #=> false 4 | :roland_barthes.is_a? Symbol #=> true 5 | -------------------------------------------------------------------------------- /examples/print-puts.rb: -------------------------------------------------------------------------------- 1 | array = [3, 2, 1] 2 | print array 3 | # Writes "[3, 2, 1]" to $stdout 4 | puts array 5 | # Writes "3\n2\n1\n" to $stdout 6 | $stderr.puts 2, 4, 6 7 | # Writes "2\n4\n6\n" to $stderr 8 | proverb = "Ab igne ignem capere" 9 | sez = "--Cicero" 10 | print proverb, sez 11 | # Writes "Ab igne ignem capere--Cicero" to $stdout 12 | puts proverb, sez 13 | # Writes "Ab igne ignem capere\n--Cicero\n" to $stdout 14 | -------------------------------------------------------------------------------- /examples/proc-calling.rb: -------------------------------------------------------------------------------- 1 | person = ->(age) do 2 | "#{age}: (" + case age 3 | when (0..12) then 'child' 4 | when (13..19) then 'teenager' 5 | when (20..59) then 'adult' 6 | else 'pensioner' 7 | end + ")" 8 | end 9 | person.call(19) #=> "19: (teenager)" 10 | person.(101) #=> "101: (pensioner)" 11 | person.yield 8 #=> "8: (child)" 12 | person[10] #=> "10: (child)" 13 | person === 26 #=> "26: (adult)" 14 | -------------------------------------------------------------------------------- /examples/proc-parameters.rb: -------------------------------------------------------------------------------- 1 | ->(a, b=2){ [a,b] } 2 | lambda {|a,b=2| [a,b]} 3 | Proc.new do |a, b=2| 4 | [a, b] 5 | end 6 | -------------------------------------------------------------------------------- /examples/putback-invalid-byte-sequence.rb: -------------------------------------------------------------------------------- 1 | source, dest = "a\u6543bc", "" 2 | source.setbyte(2,0) 3 | ec = Encoding::Converter.new('utf-8', 'ascii') 4 | until source.empty? 5 | state = ec.primitive_convert(source, dest) 6 | p [source, dest, *ec.primitive_errinfo] 7 | ec.putback if state == :invalid_byte_sequence 8 | end 9 | #=> ["\x83bc", "a", :invalid_byte_sequence, "UTF-8", "US-ASCII", "\xE6", "\x00"] 10 | #=> ["bc", "a", :invalid_byte_sequence, "UTF-8", "US-ASCII", "\x83", ""] 11 | #=> ["", "abc", :finished, nil, nil, nil, nil] 12 | -------------------------------------------------------------------------------- /examples/question-mark-suffix-non-predicate.rb: -------------------------------------------------------------------------------- 1 | 3.5.infinite? #=> nil 2 | 3 | 3.5.fdiv(0.0) #=> Infinity 4 | 3.5.fdiv(0.0).infinite? #=> 1 5 | 6 | -10.quo(0.0) #=> -Infinity 7 | -10.quo(0.0).infinite? #=> -1 8 | -------------------------------------------------------------------------------- /examples/raise-multiple-arguments.rb: -------------------------------------------------------------------------------- 1 | begin 2 | raise SystemExit.new(1), "Abnormal exit" 3 | rescue SystemExit => e 4 | "Caught exit with status #{e.status}: #{e.message}" 5 | end #=> "Caught exit with status 1: Abnormal exit" 6 | 7 | def move 8 | raise LocalJumpError, "Try hopping or skipping", ["Buy Thriller DVD", 9 | "[redacted]", 10 | "Rise up, legs akimbo"] 11 | rescue => e 12 | return "#{e.class}: <#{e.message}> from <#{e.backtrace.first}>??" 13 | end 14 | 15 | move 16 | #=> "LocalJumpError: from ??" 17 | -------------------------------------------------------------------------------- /examples/raise-one-argument.rb: -------------------------------------------------------------------------------- 1 | raise TypeError 2 | #=> # 3 | 4 | raise "Quantum entanglement failed" 5 | #=> 6 | 7 | obj = Object.new 8 | def obj.exception 9 | NameError.new("We're supposed to be anonymous!") 10 | end 11 | raise obj 12 | #=> # 13 | -------------------------------------------------------------------------------- /examples/ran-begin-end.rb: -------------------------------------------------------------------------------- 1 | Range.new(1.0, 3.0).begin #=> 1.0 2 | (?a...?z).end #=> "z" 3 | (:abc..:cba).first(10) 4 | #=> [:abc, :abd, :abe, :abf, :abg, :abh, :abi, :abj, :abk, :abl] 5 | (Rational(1,5)..1).first #=> (1/5) 6 | -------------------------------------------------------------------------------- /examples/ran-equal.rb: -------------------------------------------------------------------------------- 1 | (5..6) == (5..6) #=> true 2 | (:an..:other) == (:an...:other) #=> false 3 | (-Float::INFINITY..Float::INFINITY).eql?(Range.new(0, Float::INFINITY)) #=> false 4 | -------------------------------------------------------------------------------- /examples/ran-iterate.rb: -------------------------------------------------------------------------------- 1 | (-1..1).each {|n| print "%2d" % n} 2 | # -1 0 1 3 | (1.0..2.0).step(0.1).reduce(:+) #=> 16.5 4 | -------------------------------------------------------------------------------- /examples/ran-literal.rb: -------------------------------------------------------------------------------- 1 | (0..9).to_a 2 | #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 | (0...9).to_a 4 | #=> [0, 1, 2, 3, 4, 5, 6, 7, 8] 5 | ?a..?z 6 | -------------------------------------------------------------------------------- /examples/ran-membership.rb: -------------------------------------------------------------------------------- 1 | ages = 18..30 2 | ages.include? 505 #=> false 3 | ages.include? 25.0 #=> true 4 | ages.include? 14 #=> false 5 | (18...30).include? 30 #=> false 6 | (Rational(1,10)..Rational(10, 1)).cover? 3 #=> true 7 | (:above..:below).include? :angels #=> false 8 | (:above..:below).cover? :angels #=> true 9 | -------------------------------------------------------------------------------- /examples/ran-new.rb: -------------------------------------------------------------------------------- 1 | Range.new(0, 9).to_a 2 | #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 | Range.new(0, 9, true).to_a 4 | #=> [0, 1, 2, 3, 4, 5, 6, 7, 8] 5 | Range.new(?a, ?z) 6 | -------------------------------------------------------------------------------- /examples/random-new.rb: -------------------------------------------------------------------------------- 1 | prng = Random.new 42 2 | prng.seed #=> 42 3 | Random.new.seed #=> 218115049506821704411283774120640050107 4 | -------------------------------------------------------------------------------- /examples/random-rand.rb: -------------------------------------------------------------------------------- 1 | prng = Random.new 0xDEAF 2 | prng.rand #=> 0.9812733995904889 3 | prng.rand 30 #=> 1 4 | prng.rand Math::PI #=> 0.21283178272607403 5 | prng.rand(2**10..2**100) #=> 1018356302920191178791579529869 6 | prng.bytes 5 #=> "\xA4.~\xAC\xAB" 7 | -------------------------------------------------------------------------------- /examples/rational-constructor.rb: -------------------------------------------------------------------------------- 1 | Rational(12) #=> (12/1) 2 | Rational(67, 31) #=> (67/31) 3 | Rational('7/8') #=> (7/8) 4 | Rational(500, 100) #=> (5/1) 5 | Rational(3.5) #=> (7/2) 6 | Rational(Rational(1, 2), Rational(1, 4)) #=> (2/1) 7 | -------------------------------------------------------------------------------- /examples/rational-float.rb: -------------------------------------------------------------------------------- 1 | 0.7 * 0.7 #=> 0.48999999999999994 2 | r = Rational(7, 10) * Rational(7, 10) #=> (49/100) 3 | r.to_f #=> 0.49 4 | -------------------------------------------------------------------------------- /examples/rational-numerator-denominator.rb: -------------------------------------------------------------------------------- 1 | [41.numerator, 41.denominator] #=> [41, 1] 2 | r = Rational(136, 153) 3 | [r.numerator, r.denominator] #=> [8, 9] 4 | f = r.to_f 5 | [f.numerator, f.denominator] #=> [2001599834386887, 2251799813685248] 6 | r = f.rationalize 7 | [r.numerator, r.denominator] #=> [8, 9] 8 | -------------------------------------------------------------------------------- /examples/rational-rationalize.rb: -------------------------------------------------------------------------------- 1 | 1.7.to_r #=> (7656119366529843/4503599627370496) 2 | 1.7.to_r.to_f #=> 1.7 3 | 1.7.rationalize #=> (17/10) 4 | 1.7.rationalize.to_f #=> 1.7 5 | 12345.6789.rationalize 0.1 #=> (37037/3) 6 | '9/10'.to_r #=> (9/10) 7 | -------------------------------------------------------------------------------- /examples/receiver-dot-selector-syntax.rb: -------------------------------------------------------------------------------- 1 | "esrever".reverse #=> "reverse" 2 | (1 + 2).succ #=> 4 3 | -------------------------------------------------------------------------------- /examples/receiver-selector-arguments-syntax.rb: -------------------------------------------------------------------------------- 1 | cabin_dwellers = [] 2 | cabin_dwellers.push(:kaczynski, :roosevelt, :thoreau) 3 | #=> [:kaczynski, :roosevelt, :thoreau] 4 | cabin_dwellers.unshift(cabin_dwellers.pop()) 5 | #=> [:thoreau, :kaczynski, :roosevelt] 6 | cabin_dwellers.insert(1, cabin_dwellers.pop) 7 | #=> [:thoreau, :roosevelt, :kaczynski] 8 | -------------------------------------------------------------------------------- /examples/redo.rb: -------------------------------------------------------------------------------- 1 | loop do 2 | puts "Password: " 3 | password = gets.chomp 4 | unless [/\d/, /[A-Z]/, /[a-z]/].all?{|pat| pat =~ password} 5 | $stderr.puts "Passwords must contain uppercase, lowercase, and digits" 6 | redo 7 | end 8 | unless password.size > 8 9 | $stderr.puts "Passwords must be at least 9 characters long" 10 | redo 11 | end 12 | puts "Thanks. Confirm password: " 13 | unless password == gets.chomp 14 | $stderr.puts "The passwords entered do not match!" 15 | redo 16 | end 17 | break 18 | end 19 | -------------------------------------------------------------------------------- /examples/reg-possessive.rb: -------------------------------------------------------------------------------- 1 | '123' =~ /^\d(2|4|6|8)?\d\d/ #=> 0 2 | '123' =~ /^\d(2|4|6|8)?+\d\d/ #=> nil 3 | 'The "programmer" said...' =~ /"[[:graph:]]*"/ #=> 4 4 | 'The "programmer" said...' =~ /"[[:graph:]]*+"/ #=> nil 5 | -------------------------------------------------------------------------------- /examples/regexp-alternation.rb: -------------------------------------------------------------------------------- 1 | %w{cat ls catls cats ca}.grep /\A(cat|ls)\Z/ 2 | #=> ["cat", "ls"] 3 | (%w{cat ls(1) echo(1) cats} << '').grep /\A((cat|ls)\(\d+\)|echo|)\Z/ 4 | #=> ["ls(1)", ""] 5 | %w{xx xy yX yy yz zz xixi xz}.grep /\A(x(?i:x|y)|y(?i:x|y)|z)\Z/ 6 | #=> ["xx", "xy", "yX", "yy"] 7 | -------------------------------------------------------------------------------- /examples/regexp-anchors.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | str = "Hit him on the head\n" + 3 | "Hit him on the head with a 2×4\n" 4 | str.scan(/^Hit/) #=> ["Hit", "Hit"] 5 | str.scan(/\AHit/) #=> ["Hit"] 6 | str =~/head$/ #=> 15 7 | str.scan(/\d\Z/) #=> ["4"] 8 | str =~ /\d\z/ #=> nil 9 | str.scan(/\b\d/) #=> ["2", "4"] 10 | str.scan(/\w+\B/) 11 | #=> ["Hi", "hi", "o", "th", "hea", "Hi", "hi", "o", "th", "hea", "wit"] 12 | -------------------------------------------------------------------------------- /examples/regexp-backreferences-lvars.rb: -------------------------------------------------------------------------------- 1 | phrase = 'Aut disce aut discede' 2 | /(?\w+) (?\w+) (?<_or>\k) (?\w+)/i =~ phrase 3 | [either, learn, _or, leave] #=> ["Aut", "disce", "aut", "discede"] 4 | /\A(ab|ex) (?uno) (?#{learn})/ =~ 'Ex uno disce omnes' #=> nil 5 | learn #=> "disce" 6 | defined?(one) #=> nil 7 | 'Aut...' =~ /Aut(?\.{3})/ #=> 0 8 | defined?(ellipsis) #=> nil 9 | -------------------------------------------------------------------------------- /examples/regexp-backreferences.rb: -------------------------------------------------------------------------------- 1 | /(.)\1/ =~ 'UU' #=> 0 2 | $1 #=> 'U' 3 | %w{emaciate usurious enyzyme fists overdo unkind}. 4 | grep(/\A(?[aeiou])(?[^aeiou])\w+\k\Z/) 5 | #=> ["emaciate", "enyzyme", "overdo"] 6 | pattern = %r{\A(?[a-z]+)://(?[^/]+)(?::\d+)} 7 | match = pattern.match 'http://example.ORG:80/' 8 | #=> # 9 | match[:host] #=> "example.ORG" 10 | $1 #= "http" 11 | $~[:scheme] #=> "http" 12 | -------------------------------------------------------------------------------- /examples/regexp-capturing.rb: -------------------------------------------------------------------------------- 1 | time = /\A(?(0\d|1[0-9]|2[0-3])):(?([1-5]\d|0\d))\Z/ 2 | match = time.match '11:30' 3 | match[:hours] #=> "11" 4 | match[:minutes] #=> "30" 5 | -------------------------------------------------------------------------------- /examples/regexp-classes.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | /\A[^1-9][xX][[:xdigit:]][[:space:]] = [[:digit:]]{2}\Z/ =~ '0xf = 15' 3 | chars = (200..3000).map{|c| c.chr 'utf-8'} 4 | chars.grep(/[[:digit:]]/).first(10) 5 | #=> ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"] 6 | chars.grep(/[[:upper:]]/).first(10) 7 | #=> ["È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ"] 8 | chars.grep(/[[:lower:]]/).first(10) 9 | #=> ["ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è"] 10 | -------------------------------------------------------------------------------- /examples/regexp-group-options.rb: -------------------------------------------------------------------------------- 1 | %w{CASE case CAse caSE cASe casE}.grep /(?i:ca)se/ 2 | #=> ["case", "CAse"] 3 | %W{fin\n fi\n\n \n\n fin\r\n find}.grep /f.{2}(?m:.)\Z/ 4 | #=> ["fin\n", "fin\r\n", "find"] 5 | /space(?x: m 6 | a 7 | n # or 'woman'... 8 | ) #\d+/ =~ 'spaceman #47' 9 | #=> 0 10 | /x(?xi: 11 | i)/ =~ 'xI' #=> 0 12 | -------------------------------------------------------------------------------- /examples/regexp-literal.rb: -------------------------------------------------------------------------------- 1 | /pat/i =~ 'Pattern' 2 | /1\/2/ =~ '1/2' 3 | %r{1/2} =~ '1/2' 4 | -------------------------------------------------------------------------------- /examples/regexp-matching.rb: -------------------------------------------------------------------------------- 1 | '23' =~ /a/ #=> nil 2 | /\A0x[[:xdigit:]]+\Z/i =~ '0XA55E' #=> 0 3 | /\D/ =~ '2 + 3' #=> 1 4 | '33 + 41'.match /(\d+) [-+] (\d+)/ #=> # 5 | /\./.match "" #=> nil 6 | -------------------------------------------------------------------------------- /examples/regexp-options.rb: -------------------------------------------------------------------------------- 1 | 3.times.map{|n| /#{n}/} #=> [/0/, /1/, /2/] 2 | 3.times.map{|n| /#{n}/o} #=> [/0/, /0/, /0/] 3 | /case/i =~ 'Case' #=> 0 4 | /Case/i =~ 'cAsE' #=> 0 5 | /.../m =~ "a\nb" #=> 0 6 | /f r e e # comment 7 | -spac ing/x =~ 'free-spacing' #=> 0 8 | /EUC-JP/e.encoding #=> # 9 | -------------------------------------------------------------------------------- /examples/regexp-quantifiers.rb: -------------------------------------------------------------------------------- 1 | %w{0bB0 0b1111010 0b(0|1)+ 0B1}.grep /\A0[bB](0|1)+\Z/ 2 | #=> ["0b1111010", "0B1"] 3 | %w{+Infinity -Infinity Infinity NaN -NaN}.grep /\A(([+-]?Infinity)|NaN)\Z/ 4 | #=> ["+Infinity", "-Infinity", "Infinity", "NaN"] 5 | %w{0x 0xfeed food 0xae!}.grep /\A0x[[:xdigit:]]*\Z/ 6 | #=> ["0x", "0xfeed"] 7 | %w{0 01 08 o 065 0123 051171 082 0o0}.grep /\A0[0-7]{2,4}\Z/ 8 | #=> ["065", "0123"] 9 | %w{NaN+ a4 00.0 3. 2\n.7 07 42 -Infinity +34.21 -0.54 1.23232 Infinity.2}.grep \ 10 | /\A(NaN| # The string 'NaN', OR 11 | [-+]?( # An optional sign, then 12 | 13 | Infinity| # The string 'Infinity', OR 14 | 15 | ([1-9]\d+|\d) # A non-zero digit followed by one or more digits, OR 16 | # a single digit by itself, then 17 | (\.\d{1,4})? # optionally, a literal '.' followed by 1-4 digits 18 | ) 19 | )\Z/x #=> ["42", "-Infinity", "+34.21", "-0.54"] 20 | -------------------------------------------------------------------------------- /examples/regexp-readability.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | # A naïve pattern to match a human name 3 | title = /(?:(?Mrs?|M(?:aster|s)|Dr|Sir)[[:blank:]])?/ 4 | name_part = /[[:upper:]][[:alpha:]-]+ # Double-barrelled names are allowed, but 5 | # names can't start or end with hyphens 6 | [[:alpha:]] # i.e. names must contain at least three characters 7 | /x 8 | name_mid_part = /(?: 9 | (?: 10 | (?:[[:lower:]]{1,3})| # e.g. 'von', 'y', or 'de' 11 | (?:[[:upper:]]\.) | # middle initial 12 | (?:#{name_part}) 13 | )[[:blank:]])/x 14 | name = /(?<name>#{name_part}[[:blank:]] # A forename 15 | #{name_mid_part}* # Any number of middle names 16 | #{name_part} # A surname or family name 17 | )/x 18 | suffix = /(?:[[:blank:]](?<suffix>[JS]r\.|[IVX]+(?# Roman numerals)))?/ 19 | full_name = /\A#{title}#{name}#{suffix}\Z/ 20 | ['Mr Harvey Duchamp II', 'Dr Ludwig von Mises', 'William S. Burroughs', 21 | 'Ms Henrietta Cartwright-Stevens', 'Paul Erdős', 'Anonymous', '2 by 4', 22 | 'Master Elijah Humphrey Pennington Hargreeves Jr.'].grep full_name 23 | #=> ["Mr Harvey Duchamp II", "Dr Ludwig von Mises", "William S. Burroughs", 24 | # "Ms Henrietta Cartwright-Stevens", "Paul Erdős", 25 | # "Master Elijah Humphrey Pennington Hargreeves Jr."] 26 | -------------------------------------------------------------------------------- /examples/regexp-specify-encoding.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | utf8 = /caf(e|é)/ 3 | utf8.encoding #=> #<Encoding:UTF-8> 4 | iso88591_a = Regexp.new('caf(e|é)'.encode('iso-8859-1')) 5 | iso88591_b = Regexp.new(utf8.source.encode('iso-8859-1')) 6 | iso88591_a == iso88591_b #=> true 7 | iso88591_a.encoding #=> #<Encoding:ISO-8859-1> 8 | -------------------------------------------------------------------------------- /examples/regexp-split.rb: -------------------------------------------------------------------------------- 1 | # Extract sequences of consecutive digits 2 | 'one: 1, ten: 10, one-hundred: 100'.scan(/\d+/) 3 | #=> ["1", "10", "100"] 4 | 5 | # Separate a String into substrings separated by ', ' 6 | 'Asia, Africa, North America, South America, Antarctica, Europe, Australia'. 7 | split(/, /) 8 | #=> ["Asia", "Africa", "North America", "South America", 9 | # "Antarctica", "Europe", "Australia"] 10 | -------------------------------------------------------------------------------- /examples/regexp-validation.rb: -------------------------------------------------------------------------------- 1 | # Does a String contain a digit? 2 | /\d/ =~ 'two: 2' #=> 5 3 | # (Yes, starting at this fifth character) 4 | /\d/ =~ 'Nope' #=> nil 5 | # (No) 6 | 7 | # Which Strings in an Array contain 'cat' case-insensitively? 8 | %w{dogma verification wildcat dogfish medicate underdog Catholicism}.grep /cat/i 9 | #=> ["verification", "wildcat", "medicate", "Catholicism"] 10 | -------------------------------------------------------------------------------- /examples/regexps-zero-width.rb: -------------------------------------------------------------------------------- 1 | "foresight".sub(/(?!s)ight/, 'ee') #=> "foresee" 2 | "anterior".sub(/(?<!eleph)an(?=t)/, 'pos') #=> "posterior" 3 | %w{An abbess abjures an oblate 4 | for his absurd abacus}.grep /\A.b(?![four]).{4}(?!i?e)\z/ 5 | #=> ["abbess", "oblate", "absurd", "abacus"] 6 | -------------------------------------------------------------------------------- /examples/remove-method.rb: -------------------------------------------------------------------------------- 1 | class Parent 2 | def says 3 | "Tidy your room!" 4 | end 5 | end 6 | 7 | class Child < Parent 8 | def says 9 | "In a minute..." 10 | end 11 | end 12 | 13 | Child.new.says #=> "In a minute..." 14 | 15 | class Child 16 | remove_method :says 17 | end 18 | 19 | Child.new.says #=> "Tidy your room!" 20 | -------------------------------------------------------------------------------- /examples/reopened-class.rb: -------------------------------------------------------------------------------- 1 | 'hello'.length #=> 5 2 | class String 3 | def length 4 | 'How long is a piece of string?' 5 | end 6 | end 7 | 'hello'.length #=> 'How long is a piece of string?' 8 | -------------------------------------------------------------------------------- /examples/required-arguments-with-optional-arguments.rb: -------------------------------------------------------------------------------- 1 | def required_optional(a,b=1) end 2 | def required_required_optional(a,b,c=1) end 3 | def optional_required(a=1,b) end 4 | def optional_optional_required(a=1,b=2,c) end 5 | -------------------------------------------------------------------------------- /examples/required-arguments.rb: -------------------------------------------------------------------------------- 1 | class Llama 2 | def laugh(how, volume) 3 | puts volume == :loudly ? how.upcase : how 4 | end 5 | end 6 | Llama.new.laugh 7 | #=> ArgumentError: wrong number of arguments (0 for 2) 8 | Llama.new.laugh(:snicker) 9 | #=> ArgumentError: wrong number of arguments (1 for 2) 10 | Llama.new.laugh(:chortle,:softly) 11 | #=> chortle 12 | Llama.new.laugh(:guffaw,:loudly) 13 | #=> GUFFAW 14 | Llama.new.laugh(:ho, :ho, :ho) 15 | #=> ArgumentError: wrong number of arguments (3 for 2) 16 | -------------------------------------------------------------------------------- /examples/rescue-clause.rb: -------------------------------------------------------------------------------- 1 | begin 2 | # 1. Raises a RuntimeError with 'Disaster' as the message 3 | raise "Disaster" 4 | # RuntimeError is a subclass of StandardError, so this clause matches 5 | # the exception raised above and assigns it to local variable e 6 | rescue => e 7 | e.message 8 | end #=> 'Disaster' 9 | -------------------------------------------------------------------------------- /examples/respond-to-method-missing.rb: -------------------------------------------------------------------------------- 1 | object = Object.new 2 | def object.method_missing(selector) 3 | selector == :colour ? :red : super 4 | end 5 | object.respond_to? :colour #=> false 6 | object.colour #=> :red 7 | -------------------------------------------------------------------------------- /examples/respond-to-private.rb: -------------------------------------------------------------------------------- 1 | 'uninitialized'.private_methods.include? :initialize #=> true 2 | 'uninitialized'.respond_to? :initialize #=> false 3 | 'uninitialized'.respond_to? :initialize, true #=> true 4 | -------------------------------------------------------------------------------- /examples/respond-to.rb: -------------------------------------------------------------------------------- 1 | Math::PI #=> 3.141592653589793 2 | Math::PI.respond_to? :floor #=> true 3 | Math::PI.floor #=> 3 4 | Math::PI.methods.all?{|m| Math::PI.respond_to? m} #=> true 5 | Math::PI.respond_to? :door #=> false 6 | Math::PI.door #=> NoMethodError 7 | -------------------------------------------------------------------------------- /examples/rest-arguments.rb: -------------------------------------------------------------------------------- 1 | def zero_or_more(*rest) 2 | rest.join(', ') 3 | end 4 | zero_or_more #=> "" 5 | zero_or_more(1) #=> "1" 6 | zero_or_more(1,2,3) #=> "1, 2, 3" 7 | -------------------------------------------------------------------------------- /examples/rest-parameter-with-super.rb: -------------------------------------------------------------------------------- 1 | class Parent 2 | def do_chores(*chores) 3 | end 4 | end 5 | 6 | class Child < Parent 7 | def do_chores(*) 8 | # our processing 9 | super 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /examples/self-as-the-implicit-receiver.rb: -------------------------------------------------------------------------------- 1 | self #=> main 2 | self.class #=> Object 3 | 4 | class Classy 5 | self 6 | end #=> Classy 7 | 8 | class Classy 9 | self.class 10 | end #=> Class 11 | 12 | class Classy 13 | def methodical 14 | self 15 | end 16 | end 17 | Classy.new.methodical #=> #<Classy:0x90d2268> 18 | -------------------------------------------------------------------------------- /examples/send-if-respond-to.txt: -------------------------------------------------------------------------------- 1 | <literal><replaceable>receiver</replaceable>.<replaceable>selector</replaceable> if 2 | <replaceable>receiver</replaceable>.respond_to?(:<replaceable>selector</replaceable>)</literal> 3 | -------------------------------------------------------------------------------- /examples/sending-a-message.rb: -------------------------------------------------------------------------------- 1 | "wool".size #=> 4 2 | "wool".send(:size) #=> 4 3 | -------------------------------------------------------------------------------- /examples/shebang-shell.txt: -------------------------------------------------------------------------------- 1 | run@paint:~ → chmod +x shebang.rb 2 | run@paint:~ → ./shebang.rb 3 | The whole shebang 4 | -------------------------------------------------------------------------------- /examples/shebang.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | puts "The whole shebang" 3 | -------------------------------------------------------------------------------- /examples/single-quoted-string-literal-q.rb: -------------------------------------------------------------------------------- 1 | %q&'\n& #=> "'\\n" 2 | %q. 3 | s 4 | t 5 | r 6 | i 7 | n 8 | g 9 | . #=> "\n s\n t\n r\n i\n n\n g\n " 10 | %q<<b>bold</b>> #=> "<b>bold</b>" 11 | -------------------------------------------------------------------------------- /examples/size-selector.rb: -------------------------------------------------------------------------------- 1 | 4.size #=> 4 2 | [:one, :two, :three, :four].size #=> 4 3 | File.open('/tmp/four','w'){ print '1' * 4} 4 | File.new('/tmp/four').size #=> 4 5 | 'five'.size #=> 4 6 | -------------------------------------------------------------------------------- /examples/spaceship-selector.rb: -------------------------------------------------------------------------------- 1 | 2 <=> 2 #=> 0 2 | 2 <=> 1 #=> 1 3 | 2 <=> 3 #=> -1 4 | 2 <=> :two #=> nil 5 | -------------------------------------------------------------------------------- /examples/splat-arguments.rb: -------------------------------------------------------------------------------- 1 | def one(argument) 2 | "One argument: #{argument}" 3 | end 4 | 5 | def three(first, second, third) 6 | "Three arguments: #{first}, #{second}, #{third}" 7 | end 8 | 9 | array = [1, 2, 3] 10 | one(array) #=> "One argument: [1, 2, 3]" 11 | three(array) #=> ArgumentError: wrong number of arguments (1 for 3) 12 | three(*array) #=> "Three arguments: 1, 2, 3" 13 | three(1, 2, 3) #=> "Three arguments: 1, 2, 3" 14 | -------------------------------------------------------------------------------- /examples/splat-lvalue.rb: -------------------------------------------------------------------------------- 1 | *a = 1 2 | a #=> [1] 3 | 4 | a, *b = 1, 2, 3, 4 5 | a #=> 1 6 | b #=> [2, 3, 4] 7 | 8 | a, *b, c = 1, 2, 3, 4 9 | a #=> 1 10 | b #=> [2, 3] 11 | c #=> 4 12 | -------------------------------------------------------------------------------- /examples/splat-rvalue.rb: -------------------------------------------------------------------------------- 1 | a, b = *1 2 | a #=> 1 3 | b #=> nil 4 | 5 | a, b = *[1, 2] 6 | a #=> 1 7 | b #=> 2 8 | 9 | a, b, c = *(1..2), 3 10 | a #=> 1 11 | b #=> 2 12 | c #=> 3 13 | -------------------------------------------------------------------------------- /examples/sprintf-arguments.rb: -------------------------------------------------------------------------------- 1 | '%2$s %1$s' % [:first, :second] 2 | #=> "second first" 3 | '%0*d' % [10, 2] 4 | #=> "0000000002" 5 | '%*1$1$d%*2$2$d%*3$3$d%*4$4$d%*5$5$d' % [*1..5] 6 | #=> "1 2 3 4 5" 7 | '%.*2$1$f %.*3$1$f %.*4$1$f' % [Math::PI, 0, 2, 4] 8 | #=> "3 3.14 3.1416" 9 | -------------------------------------------------------------------------------- /examples/sprintf-bases.rb: -------------------------------------------------------------------------------- 1 | '2:%b, 8:%o, 16:%x' % [200, 800, 1600] 2 | #=> "2:11001000, 8:1440, 16:640" 3 | '%#B' % ('%d' % 032) 4 | #=> "0B11010" 5 | '% x; %#x; %#010X' % [-54].*(3) 6 | #=> "-36; 0x..fca; 0X..FFFFCA" 7 | -------------------------------------------------------------------------------- /examples/sprintf-hash.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | %q@ 3 | Subject: Are You Our Missing Winner? 4 | To: %{email} 5 | 6 | Dear %{name}, 7 | Congratulations! You have been selected to receive a cash prize 8 | of £%.2<prize>f!!! Your name was selected at random by our 9 | supercomputer to be a millionaire!?! But hurry, you must claim 10 | your fortune by **%.19<deadline>p** or it will be gifted 11 | to the next name on our shortlist. 12 | 13 | Hurry. Please act now. 14 | @ % {name: 'A. Patsy', prize: 2_883_712.28271, email: 'mark@aol.com', 15 | deadline: Time.now.utc + (60+24*3600)} 16 | #=> 17 | #Subject: Are You Our Missing Winner? 18 | #To: mark@aol.com 19 | # 20 | #Dear A. Patsy, 21 | #Congratulations! You have been selected to receive a cash prize 22 | #of £2883712.28!!! Your name was selected at random by our 23 | #supercomputer to be a millionaire!?! But hurry, you must claim 24 | #your fortune by **2010-06-18 22:23:52** or it will be gifted 25 | #to the next name on our shortlist. 26 | # 27 | #Hurry. Please act now. 28 | -------------------------------------------------------------------------------- /examples/sprintf-notation.rb: -------------------------------------------------------------------------------- 1 | '%f' % Math::PI 2 | #=> "3.141593" 3 | '%e' % Math::E 4 | #=> "2.718282e+00" 5 | '%E' % -0.0000231 6 | #=> "-2.310000E-05" 7 | '%g %.G %g' % [9_000, 12e-8, -12000000000.5] 8 | #=> "9000 1E-07 -1.2e+10" 9 | '%.20a' % 678.19e100 10 | #=> "0x1.8394d0b22721f0000000p+341" 11 | -------------------------------------------------------------------------------- /examples/sprintf-textual.rb: -------------------------------------------------------------------------------- 1 | '%s %c %s' % ['Horses', 52, 'Courses'] 2 | #=> "Horses 4 Courses" 3 | '%p =~ "%.5s..."' % [/[aeiou]/i, 'A slow, red fox'] 4 | #=> "/[aeiou]/i =~ \"A slo...\"" 5 | -------------------------------------------------------------------------------- /examples/sprintf-width.rb: -------------------------------------------------------------------------------- 1 | digits = [*(1..9)] 2 | '%1s' % digits.join 3 | #=> "123456789" 4 | '%20s = %#x' % [digits.join, digits.reduce(:+)] 5 | #=> " 123456789 = 0x2d" 6 | '>%0-20X<' % [*digits.join.bytes].join 7 | #=> ">6DEC6BD4A460909 <" 8 | -------------------------------------------------------------------------------- /examples/stdin-stdout-stderr.rb: -------------------------------------------------------------------------------- 1 | STDIN.fileno #=> 0 2 | STDOUT.fileno #=> 1 3 | STDERR.fileno #=> 2 4 | -------------------------------------------------------------------------------- /examples/stdout-redirection.rb: -------------------------------------------------------------------------------- 1 | puts "STDOUT" # Written to STDOUT 2 | $stdout = STDERR 3 | puts "STDERR" # Written to STDERR 4 | $stdout = STDOUT 5 | puts "STDOUT" # Written to STDOUT 6 | 7 | # From the command-line: 8 | # $ ruby stdout-redirection.rb 9 | # STDOUT 10 | # STDERR 11 | # STDOUT 12 | # $ ruby stdout-redirection.rb 2>/dev/null 13 | # STDOUT 14 | # STDOUT 15 | -------------------------------------------------------------------------------- /examples/string-case.rb: -------------------------------------------------------------------------------- 1 | str = 'cAsE-sEnSiTiVe' 2 | str.downcase #=> "case-sensitive" 3 | str.upcase #=> "CASE-SENSITIVE" 4 | str.capitalize #=> "Case-sensitive" 5 | str.swapcase #=> "CaSe-SeNsItIvE" 6 | -------------------------------------------------------------------------------- /examples/string-checksum.rb: -------------------------------------------------------------------------------- 1 | str = 'need-to-know' 2 | str.sum #=> 1176 3 | str.sum 4 #=> 8 4 | str.sum -10 #=> 1176 5 | str.crypt('a.') #=> "a.YKZnbNk2rOs" 6 | str.crypt('w8') #=> "w8Y/hB.q9SVxo" 7 | -------------------------------------------------------------------------------- /examples/string-comparison.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ?a < ?A #=> false 3 | 'pre' < 'prefix' #=> true 4 | ?Β <=> ?β #=> -1 5 | ?α < ?β #=> true 6 | '11' > '100' #=> true 7 | ?a.casecmp ?A #=> 0 8 | 'epsilON'.casecmp 'Epsilon' #=> 0 9 | ?Σ.casecmp ?ς #=> -1 10 | -------------------------------------------------------------------------------- /examples/string-concat.rb: -------------------------------------------------------------------------------- 1 | str = 'con' #=> "con" 2 | str + 'cat' #=> "concat" 3 | str #=> "con" 4 | str << 'cat' << 101 << 'nation' #=> "concatenation" 5 | str #=> "concatenation" 6 | -------------------------------------------------------------------------------- /examples/string-count-delete.rb: -------------------------------------------------------------------------------- 1 | s = 'Aaa bbb cc dd e' 2 | s.count('Aa-e') #=> 11 3 | s.count(?a, ?b) #=> 0 4 | s.count('a-d') #=> 9 5 | s.delete!('b-e', '^c') #=> "Aaa cc " 6 | s.count('a-e', '^b') #=> 4 7 | s.count('A-Za-z ') #=> 9 8 | -------------------------------------------------------------------------------- /examples/string-debug.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | str = "\"a\b\u{63}\t\x12\u{200}\"" 3 | str.inspect #=> "\"a\bc\t\u0012Ȁ\"" 4 | str.dump #=> "\"a\bc\t\x12\u{200}\"" 5 | -------------------------------------------------------------------------------- /examples/string-index.rb: -------------------------------------------------------------------------------- 1 | alphabet = [*?a..?z].join 2 | alphabet.index ?e #=> 4 3 | alphabet.index /[aeiou]/ #=> 0 4 | alphabet.index '~' #=> nil 5 | alphabet.index(/[[:xdigit:]]/) #=> 0 6 | alphabet.rindex(/[[:xdigit:]]/) #=> 5 7 | alphabet << alphabet 8 | alphabet.index ?e, 10 #=> 30 9 | -------------------------------------------------------------------------------- /examples/string-numeric.rb: -------------------------------------------------------------------------------- 1 | ' 34_89'.to_i #=> 3489 2 | 'b_ee_f or lamb?'.hex #=> 48879 3 | 'tofu?!?'.to_i(8) #=> 0 4 | '-23.89'.to_f #=> -23.89 5 | '4.1e6'.to_f #=> 4100000.0 6 | '3/4.2'.to_r #=> (3/4) 7 | "\t2/3+2i\t".to_c #=> ((2/3)+2i) 8 | -------------------------------------------------------------------------------- /examples/string-repetition.rb: -------------------------------------------------------------------------------- 1 | (?a..?f).map.with_index(1){|l, i| l * i}.join 2 | #=> abbcccddddeeeeeffffff 3 | -------------------------------------------------------------------------------- /examples/string-scan.rb: -------------------------------------------------------------------------------- 1 | "3^3 = 27".scan(/\d/) #=> ["3", "3", "2", "7"] 2 | cube = 'faces: 6; volume: a^3; area: 6a^2'.scan(/(\w+): ([^;]+)/).map do |k, v| 3 | [k.to_sym, v] 4 | end 5 | Hash[cube] #=> {:faces=>"6", :volume=>"a^3", :area=>"6a^2"} 6 | 'Cubes: 1^3 = 1, 2^3=8, 3^3 = 27 4^3 = ?, 5^3 = 125, 6^3 = 215'. 7 | scan(/(?<base>\d+)\^3\s*=\s*(?:(?<an>\d+)|(?<un>\?))/) do |base, answer| 8 | cube = base.to_i ** 3 9 | puts "%d^3 == %d" % [base, cube] unless cube == answer.to_i 10 | end 11 | # 4^3 == 64 12 | # 6^3 == 216 13 | -------------------------------------------------------------------------------- /examples/string-split.rb: -------------------------------------------------------------------------------- 1 | str = 'Out of memory' 2 | str.split #=> ["Out", "of", "memory"] 3 | str.split('o') #=> ["Out ", "f mem", "ry"] 4 | str.split(/o\s?/i) #=> ["", "ut ", "f mem", "ry"] 5 | str.partition('o') #=> ["Out ", "o", "f memory"] 6 | str.rpartition('o') #=> ["Out of mem", "o", "ry"] 7 | -------------------------------------------------------------------------------- /examples/string-squeeze.rb: -------------------------------------------------------------------------------- 1 | s = 'Aaa bbb cc dd e' 2 | s.squeeze #=> "Aa b c d e" 3 | s.squeeze(?a, ?b) #=> "Aaa bbb cc dd e" 4 | s.squeeze('a-d') #=> "Aa b c d e" 5 | s.squeeze('a-e', '^b') #=> "Aa bbb c d e" 6 | -------------------------------------------------------------------------------- /examples/string-sub-gsub.rb: -------------------------------------------------------------------------------- 1 | alphabet = [*?a..?f].join 2 | alphabet.sub(/U/, 'you?') #=> "abcdef" 3 | alphabet.gsub(/[b-e]/){|match| "<U+#{'%.4X' % match.ord}>"} 4 | #=> "a<U+0062><U+0063><U+0064><U+0065>f" 5 | alphabet.sub!(?V, 'for Vendetta') #=> nil 6 | '3 + -4'.sub(/(?<a>\d+) \+ -(?<b>\d+)/, 7 | "== \\k<a> - \\k<b>") 8 | #=> "== 3 - 4" 9 | subs = {?& => '&', ?> => '>'} 10 | subs.default = '?' 11 | 'You & I > he & they!'.gsub(/[[:punct:]]/, subs) 12 | #=> "You & I > he & they?" 13 | -------------------------------------------------------------------------------- /examples/string-tr.rb: -------------------------------------------------------------------------------- 1 | str = 'stuffed shirt' 2 | str.tr('st', 'S') #=> "SSuffed ShirS" 3 | str.tr('a-z', 'A-Z') #=> "STUFFED SHIRT" 4 | str.tr_s('a-z', 'A-Z') #=> "STUFED SHIRT" 5 | str.tr('shirt', 'toy') #=> "tyuffed toyyy" 6 | -------------------------------------------------------------------------------- /examples/string-unpack-float.rb: -------------------------------------------------------------------------------- 1 | "\xDB\x0FI@".unpack ?f #=> [3.1415927410125732] 2 | "\x18-DT\xFB!\t@".unpack ?d #=> [3.141592653589793] 3 | sqrt = Math.sqrt 2 #=> 1.4142135623730951 4 | [sqrt].pack(?f).unpack ?f #=> [1.4142135381698608] 5 | [sqrt].pack(?d).unpack ?d #=> [1.4142135623730951] 6 | -------------------------------------------------------------------------------- /examples/string-unpack-int.rb: -------------------------------------------------------------------------------- 1 | 'NO'.unpack ?s #=> [20302] 2 | '%.4x' % 1234 #=> "04d2" 3 | "\x04\xd2".unpack ?n #=> [1234] 4 | "\xd2\x04".unpack ?S #=> [1234] 5 | "\xd2\x04".unpack ?v #=> [1234] 6 | str = "\x52\x65\x61\x64\x52\x75\x62\x79" 7 | str.unpack ?q #=> [8746682423038797138] 8 | str.unpack('ll') #=> [1684104530, 2036495698] 9 | str.unpack('lss') #=> [1684104530, 30034, 31074] 10 | str.unpack('lscc') #=> [1684104530, 30034, 98, 121] 11 | "\u1111".unpack ?U #=> [4369] 12 | "\x7F\x85Q".unpack('w*') #=> [127, 721] 13 | "\x7F\x00\x00\x01".unpack('C4').join(?.) "127.0.0.1" 14 | -------------------------------------------------------------------------------- /examples/string-unpack-str.rb: -------------------------------------------------------------------------------- 1 | "\xba".unpack('h*') #=> ['ab'] 2 | "\xab".unpack('H*') #=> ['ab'] 3 | 'feed me?'.unpack('a2a2a*') #=> ["fe", "ed", " me?"] 4 | bin = 105.to_s 2 #=> "1100101" 5 | ?K.unpack('b7') #=> ["1101001"] 6 | "\xD2".unpack('B7') #=> ["1101001"] 7 | ")4F5A9\"!2=6)Y\n".unpack ?u #=> ["Read Ruby"] 8 | "Read Ruby=\n".unpack ?M #=> ["Read Ruby"] 9 | "UmVhZCBSdWJ5\n".unpack ?m #=> ["Read Ruby"] 10 | 11 | mem_ptr = ['Read Ruby'].pack ?P #=> "\xA0\x9C\x12\t" 12 | mem_ptr.unpack('P') #=> ["R"] 13 | mem_ptr.unpack('P*') #=> ["Read"] 14 | mem_ptr.unpack('P8') #=> ["Read Rub"] 15 | 16 | null_str = ['Read Ruby'].pack(?p) #=> "\x90N/\t" 17 | null_str.unpack ?p #=> ["Read Ruby"] 18 | -------------------------------------------------------------------------------- /examples/string-upto.rb: -------------------------------------------------------------------------------- 1 | s = 'next' 2 | s.succ! #=> 'nexu' 3 | [*s.upto('neya')] 4 | #=> ["nexu", "nexv", "nexw", "nexx", "nexy", "nexz", "neya"] 5 | ?(.upto(11.to_s).to_a 6 | #=> ["(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", 7 | # "3", "4", "5", "6", "7", "8", "9", "10", "11"] 8 | -------------------------------------------------------------------------------- /examples/string-whitespace.rb: -------------------------------------------------------------------------------- 1 | str = " orient\tate\n" 2 | str = str.lstrip #=> "orient\tate\n" 3 | str.chop! #=> "orient\tate" 4 | str.chomp #=> "orient\tate" 5 | str.chomp!('ate') #=> "orient\t" 6 | str = str.center(15, "\t") #=> "\t\t\t\torient\t\t\t\t\t" 7 | (str.strip << $/).capitalize #=> "Orient\n" 8 | -------------------------------------------------------------------------------- /examples/struct-inheritance.rb: -------------------------------------------------------------------------------- 1 | class Element < Struct.new(:name, :symbol, :atomic_number) 2 | def initialize(*args) 3 | super 4 | @poisonous = false 5 | end 6 | 7 | def poisonous? 8 | @poisonous 9 | end 10 | 11 | def poisonous=(bool) 12 | @poisonous = !!bool 13 | end 14 | end 15 | thallium = Element.new(:Thallium, :Tl, 81) 16 | thallium.symbol #=> :Tl 17 | thallium.poisonous = true 18 | thallium.poisonous? #=> true 19 | -------------------------------------------------------------------------------- /examples/struct-new.rb: -------------------------------------------------------------------------------- 1 | Element = Struct.new(:name, :symbol, :atomic_number, :mass) 2 | as = Element.new(:Arsenic, :As, 33, 74.92) 3 | as.mass #=> 74.92 4 | -------------------------------------------------------------------------------- /examples/sub-assignment.rb: -------------------------------------------------------------------------------- 1 | a, (b, c), d = 1, 2, 3, 4 2 | a #=> 1 3 | b #=> 2 4 | c #=> nil 5 | d #=> 3 6 | 7 | (a, b), c = [1, 2], 3, 4 8 | a #=> 1 9 | b #=> 2 10 | c #=> 3 11 | 12 | zero, (one, *rest) = 0, [*1..5, *6..10] 13 | zero #=> 0 14 | one #=> 1 15 | rest #=> [2, 3, 4, 5, 6, 7, 8, 9, 10] 16 | -------------------------------------------------------------------------------- /examples/substring-test.rb: -------------------------------------------------------------------------------- 1 | uname = `uname -a` 2 | #=> "Linux paint 2.6.32-23-generic #37-Ubuntu SMP Fri Jun 11 07:54:58 UTC 2010 3 | # i686 GNU/Linux\n" 4 | uname.start_with?('Linux') #=> true 5 | uname.chomp.end_with?('Linux') #=> true 6 | uname.include?('ubuntu') #=> false 7 | uname.include?(2010.to_s) #=> true 8 | uname.include?(?#) #=> true 9 | -------------------------------------------------------------------------------- /examples/substrings.rb: -------------------------------------------------------------------------------- 1 | str = 'In absentia' 2 | str[4, 4] = str[4].succ 3 | str[/t(?<ear>ia)/, :ear] = ?u 4 | str #=> "In actu" 5 | str[?c] = 'bsen' 6 | str[-1] = str[0].downcase + str[3] 7 | str #=> "In absentia" 8 | str[3..-1] = 'casu' 9 | str #=> "In casu" 10 | -------------------------------------------------------------------------------- /examples/super-module.rb: -------------------------------------------------------------------------------- 1 | module Letter 2 | def letter 3 | l = ('A'..'Z').reject{|l| Object.const_defined?(l)}.first 4 | mod = Module.new do 5 | include Letter 6 | define_method(:letter, ->{ super(); l }) 7 | end 8 | self.class.module_eval{ include Object.const_set(l, mod) } 9 | '->' 10 | end 11 | end 12 | class Alphabet 13 | include Letter 14 | def letter(n) 15 | n.times.map{super()}.join 16 | end 17 | end 18 | Alphabet.new.letter(6) #=> "->ABCDE" 19 | Alphabet.ancestors 20 | #=> [Alphabet, F, E, D, C, B, A, Letter, Object, Kernel, BasicObject] 21 | -------------------------------------------------------------------------------- /examples/super.rb: -------------------------------------------------------------------------------- 1 | class Chef 2 | def make(dish) 3 | puts "Chef: You don't want #{dish}! Try this:" 4 | :dish_of_the_day 5 | end 6 | end 7 | 8 | class Cook < Chef 9 | def make(dish) 10 | [super, :salad].join(' and ').tr('_', ' ') 11 | end 12 | end 13 | 14 | puts "Meal: " + Cook.new.make(:guinea_fowl_fricassee_with_foie_gras) 15 | #=> Chef: You don't want guinea_fowl_fricassee_with_foie_gras! Try this: 16 | # Meal: dish of the day and salad 17 | -------------------------------------------------------------------------------- /examples/symbol-creating.rb: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | :roland_barthes #=> :roland_barthes 3 | :'σύμβολον' #=> :σύμβολον 4 | %s{A proposition shows its sense.} #=> :"A proposition shows its sense." 5 | "\u22F0".to_sym #=> :⋰ 6 | -------------------------------------------------------------------------------- /examples/syswrite-write-putc.rb: -------------------------------------------------------------------------------- 1 | str = 'Prefer parchment?' 2 | $stdout.syswrite(str) #=> 17 3 | # Writes "Prefer parchment?" to $stdout 4 | $stdout.write(str) #=> 17 5 | # Writes "Prefer parchment?" to $stdout 6 | $stdout.putc(str) #=> "Prefer parchment?" 7 | # Writes "P" to $stdout 8 | STDERR.putc(str[0].ord) #=> 80 9 | # Writes "P" to STDERR 10 | -------------------------------------------------------------------------------- /examples/ternary-nil-receiver.txt: -------------------------------------------------------------------------------- 1 | <literal><replaceable>receiver</replaceable> ? <replaceable>receiver</replaceable>.<replaceable>selector</replaceable> : nil</literal> 2 | -------------------------------------------------------------------------------- /examples/ternary-operator-on-single-line.rb: -------------------------------------------------------------------------------- 1 | VOWELS = %w{a e i o u} 2 | ['d', 'e'].each do |letter| 3 | puts "#{letter} is a %s" % (VOWELS.include?(letter) ? "vowel" : "consonant") 4 | end 5 | #=> "d is a consonant" 6 | #=> "e is a vowel" 7 | -------------------------------------------------------------------------------- /examples/to_-selector.rb: -------------------------------------------------------------------------------- 1 | 10.to_s #=> "10" # String 2 | 10.to_f #=> 10.0 # Float 3 | 10.to_r #=> (10/1) # Rational 4 | 10.to_c #=> (10+0i) # Complex 5 | 10.to_enum #=> #<Enumerator: 10:each> # Enumerator 6 | -------------------------------------------------------------------------------- /examples/try_convert-selector.rb: -------------------------------------------------------------------------------- 1 | Array.try_convert [:violin] #=> [:violin] 2 | Array.try_convert :violin #=> nil 3 | -------------------------------------------------------------------------------- /examples/unboundmethod-black.rb: -------------------------------------------------------------------------------- 1 | class A 2 | def a_method 3 | puts "Definition in class A" 4 | end 5 | end 6 | 7 | class B < A 8 | def a_method 9 | puts "Definition in class B (subclass of A)" 10 | end 11 | end 12 | 13 | class C < B 14 | end 15 | -------------------------------------------------------------------------------- /examples/undef-method.rb: -------------------------------------------------------------------------------- 1 | def boo! 2 | "(goose)" 3 | end 4 | boo! #=> "(goose)" 5 | undef :boo! 6 | boo! #=> NoMethodError: undefined method `boo!' for main:Object 7 | -------------------------------------------------------------------------------- /examples/undefined-conversion-insert-output.rb: -------------------------------------------------------------------------------- 1 | source, dest = "a\ubeefbc", "" 2 | ec = Encoding::Converter.new('utf-8', 'ascii') 3 | until source.empty? 4 | if ec.primitive_convert(source, dest) == :undefined_conversion 5 | ec.insert_output("<U+%.4X>" % ec.last_error.error_char.ord) 6 | end 7 | p [source, dest, *ec.primitive_errinfo] 8 | end 9 | #=> ["bc", "a", :undefined_conversion, "UTF-8", "US-ASCII", "\xEB\xBB\xAF", ""] 10 | #=> ["", "a<U+BEEF>bc", :finished, nil, nil, nil, nil] 11 | -------------------------------------------------------------------------------- /examples/unicode-escape.rb: -------------------------------------------------------------------------------- 1 | # U+263A WHITE SMILING FACE (☺) 2 | "\u263A" #=> "☺" 3 | 4 | # U+1F090 DOMINO TILE VERTICAL-06-03 (🂐) 5 | # U+1F091 DOMINO TILE VERTICAL-06-04 (🂑) 6 | "\u{1f090 1F091}" #=> "🂐🂑" 7 | -------------------------------------------------------------------------------- /examples/unless-statement-fig.rb: -------------------------------------------------------------------------------- 1 | string = '3 free frogs' 2 | unless string =~ /^\d\./ 3 | $stderr.puts "<#{string}>: must start with a digit followed by a period" 4 | end 5 | # <3 free frogs>: must start with a digit followed by a period 6 | -------------------------------------------------------------------------------- /examples/until-loop-fig.rb: -------------------------------------------------------------------------------- 1 | def look_and_say(seed=1, max_terms) 2 | [seed].tap do |terms| 3 | until terms.size >= max_terms or terms.last == terms[-2] 4 | last = terms.last.to_s.split(//) 5 | term = [[1,last.first]] 6 | last[1..-1].each do |e| 7 | term.last.last == e ? term.last[0] += 1 : term << [1, e] 8 | end 9 | terms << term.join.to_i 10 | end 11 | end 12 | end 13 | look_and_say(7) #=> [1, 11, 21, 1211, 111221, 312211, 13112221] 14 | -------------------------------------------------------------------------------- /examples/visibility-specifiers-args.rb: -------------------------------------------------------------------------------- 1 | class C 2 | # The three following methods are public because they haven’t been 3 | # specified otherwise 4 | def pub 5 | end 6 | 7 | def pri 8 | end 9 | 10 | def pri2 11 | end 12 | 13 | # Both :pri and :pri2 are made private because their names are 14 | # given as arguments to the 'private' visibility specifier 15 | private :pri, :pri2 16 | 17 | # This method is also public; the preceding private keyword only 18 | # acts on its arguments 19 | def pro 20 | end 21 | # This method is made protected because its name is given to 22 | # the 'protected' visibility specifier 23 | protected 'pro' 24 | 25 | # This method is public because it hasn't been declared 26 | # otherwise; the previous 'protected' specifier only affects the 27 | # method it was called for 28 | def pub2 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /examples/visibility-specifiers.rb: -------------------------------------------------------------------------------- 1 | class C 2 | # This method is public because it hasn't been specified 3 | # otherwise 4 | def pub 5 | end 6 | 7 | private 8 | # This method is private because it appears after the 9 | #'private' visibility specifier 10 | def pri 11 | end 12 | 13 | # This method is also private because the previous visibility 14 | # specifier has not been overridden 15 | def pri2 16 | end 17 | 18 | protected 19 | # This method is protected because it appears after the 20 | #'protected' visibility specifier 21 | def pro 22 | end 23 | 24 | public 25 | # This method is public because the protected visibility 26 | # specifier has been explicitly overridden. Typically this would 27 | # have been defined after 'pub', removing the need for a 28 | # visibility specifier 29 | def pub2 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /examples/while-loop-fig.rb: -------------------------------------------------------------------------------- 1 | def farey(n) 2 | a, b, c, d = 0, 1, 1, n 3 | while c < n 4 | k = (n + b)/d 5 | a, b, c, d = c, d, k*c - a, k*d - b 6 | (sequence ||= []) << Rational(a, b) 7 | end 8 | sequence.unshift Rational(0, 1) 9 | end 10 | farey(4) #=> [(0/1), (1/4), (1/3), (1/2), (2/3), (3/4), (1/1)] 11 | -------------------------------------------------------------------------------- /examples/write-syswrite-printf.rb: -------------------------------------------------------------------------------- 1 | $stdout.syswrite('ex') #=> 2 2 | $stdout.write('em') #=> 2 3 | printf('%.4s', 'plumbeus') #=> nil 4 | # Writes 'exemplum' to $stdout 5 | -------------------------------------------------------------------------------- /examples/yield-semantics-break-localjump.rb: -------------------------------------------------------------------------------- 1 | Proc.new do 2 | p :alpha 3 | break 4 | p :beta 5 | end.call 6 | #=> :alpha 7 | #=> in `block in <main>': break from proc-closure (LocalJumpError) 8 | -------------------------------------------------------------------------------- /examples/yield-semantics-break.rb: -------------------------------------------------------------------------------- 1 | def inner &closure 2 | puts "\t\tmain -> outer -> inner: Calling closure <call site>" 3 | closure.call 4 | puts "\t\tmain -> outer -> inner: Called closure </call site>" 5 | end 6 | def outer 7 | puts "\tmain -> outer: Invoking inner <creation site>" 8 | inner do 9 | puts "\t\t\tmain -> outer -> inner -> closure: Breaking from closure" 10 | break 11 | puts "\t\t\tmain -> outer -> inner -> closure: Broken from closure" 12 | end 13 | puts "\tmain -> outer: Invoked outer </creation site>" 14 | end 15 | puts "main: Invoking outer" 16 | outer 17 | puts "main: Invoked outer" 18 | #=> main: Invoking outer 19 | #=> main -> outer: Invoking inner <creation site> 20 | #=> main -> outer -> inner: Calling closure <call site> 21 | #=> main -> outer -> inner -> closure: Breaking from closure 22 | #=> main -> outer: Invoked outer </creation site> 23 | #=> main: Invoked outer 24 | 25 | -------------------------------------------------------------------------------- /examples/yield-semantics-return-localjump.rb: -------------------------------------------------------------------------------- 1 | Proc.new { p :alpha; return; p :beta }.call #=> :alpha 2 | #=> in `block in <main>': unexpected return (LocalJumpError) 3 | -------------------------------------------------------------------------------- /examples/yield-semantics-return.rb: -------------------------------------------------------------------------------- 1 | def inner &closure 2 | puts "\t\tmain -> outer -> inner: Calling closure <call site>" 3 | closure.call 4 | puts "\t\tmain -> outer -> inner: Called closure </call site>" 5 | end 6 | def outer 7 | puts "\tmain -> outer: Invoking inner <creation site>" 8 | inner do 9 | puts "\t\t\tmain -> outer -> inner -> closure: Return from closure" 10 | return 11 | puts "\t\t\tmain -> outer -> inner -> closure: Returned from closure" 12 | end 13 | puts "\tmain -> outer: Invoked outer </creation site>" 14 | end 15 | puts "main: Invoking outer" 16 | outer 17 | puts "main: Invoked outer" 18 | #=> main: Invoking outer 19 | #=> main -> outer: Invoking inner <creation site> 20 | #=> main -> outer -> inner: Calling closure <call site> 21 | #=> main -> outer -> inner -> closure: Return from closure 22 | #=> main: Invoked outer 23 | 24 | -------------------------------------------------------------------------------- /fonts/.htstatic: -------------------------------------------------------------------------------- 1 | AddType application/x-ruby rb 2 | AddType application/vnd.ms-fontobject eot 3 | AddType application/x-font-ttf ttf 4 | AddType application/octet-stream woff 5 | ExpiresActive On 6 | ExpiresDefault "access plus 1 year" 7 | -------------------------------------------------------------------------------- /fonts/Barry Schwartz License.txt: -------------------------------------------------------------------------------- 1 | This font has been released into the public domain by its author, Barry Schwartz. This applies worldwide. 2 | 3 | In some countries this may not be legally possible; if so: 4 | 5 | Barry Schwartz grants anyone the right to use this work for any purpose, without any conditions, unless such conditions are required by law. -------------------------------------------------------------------------------- /fonts/eot/Inconsolata-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/Inconsolata-webfont.eot -------------------------------------------------------------------------------- /fonts/eot/Inconsolata-webfont.eot.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/Inconsolata-webfont.eot.gz -------------------------------------------------------------------------------- /fonts/eot/goudy_bookletter_1911-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/goudy_bookletter_1911-webfont.eot -------------------------------------------------------------------------------- /fonts/eot/goudy_bookletter_1911-webfont.eot.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/goudy_bookletter_1911-webfont.eot.gz -------------------------------------------------------------------------------- /fonts/eot/linlibertine_re-4.7.5-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/linlibertine_re-4.7.5-webfont.eot -------------------------------------------------------------------------------- /fonts/eot/linlibertine_re-4.7.5-webfont.eot.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/eot/linlibertine_re-4.7.5-webfont.eot.gz -------------------------------------------------------------------------------- /fonts/index.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/index.html -------------------------------------------------------------------------------- /fonts/svg/Inconsolata-webfont.svg.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/svg/Inconsolata-webfont.svg.gz -------------------------------------------------------------------------------- /fonts/svg/goudy_bookletter_1911-webfont.svg.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/svg/goudy_bookletter_1911-webfont.svg.gz -------------------------------------------------------------------------------- /fonts/ttf/Inconsolata-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/Inconsolata-webfont.ttf -------------------------------------------------------------------------------- /fonts/ttf/Inconsolata-webfont.ttf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/Inconsolata-webfont.ttf.gz -------------------------------------------------------------------------------- /fonts/ttf/OFLGoudyStM-Italic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/OFLGoudyStM-Italic-webfont.ttf -------------------------------------------------------------------------------- /fonts/ttf/OFLGoudyStM-Italic-webfont.ttf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/OFLGoudyStM-Italic-webfont.ttf.gz -------------------------------------------------------------------------------- /fonts/ttf/OFLGoudyStM-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/OFLGoudyStM-webfont.ttf -------------------------------------------------------------------------------- /fonts/ttf/OFLGoudyStM-webfont.ttf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/OFLGoudyStM-webfont.ttf.gz -------------------------------------------------------------------------------- /fonts/ttf/goudy_bookletter_1911-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/goudy_bookletter_1911-webfont.ttf -------------------------------------------------------------------------------- /fonts/ttf/goudy_bookletter_1911-webfont.ttf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/goudy_bookletter_1911-webfont.ttf.gz -------------------------------------------------------------------------------- /fonts/ttf/linlibertine_re-4.7.5-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/linlibertine_re-4.7.5-webfont.ttf -------------------------------------------------------------------------------- /fonts/ttf/linlibertine_re-4.7.5-webfont.ttf.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/ttf/linlibertine_re-4.7.5-webfont.ttf.gz -------------------------------------------------------------------------------- /fonts/woff/Inconsolata-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/woff/Inconsolata-webfont.woff -------------------------------------------------------------------------------- /fonts/woff/goudy_bookletter_1911-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/woff/goudy_bookletter_1911-webfont.woff -------------------------------------------------------------------------------- /fonts/woff/linlibertine_re-4.7.5-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/woff/linlibertine_re-4.7.5-webfont.woff -------------------------------------------------------------------------------- /fonts/woff/linlibertine_re-4.7.5-webfont.woff.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/fonts/woff/linlibertine_re-4.7.5-webfont.woff.gz -------------------------------------------------------------------------------- /notes/structure: -------------------------------------------------------------------------------- 1 | Programs 2 | Structure 3 | Interpretation 4 | Variables 5 | Closures? 6 | Object-Orientation 7 | Messages 8 | Methods 9 | Objects 10 | Classes 11 | Modules 12 | Data Types 13 | Text (incl. Regexps & Symbols) 14 | Numerics 15 | Arrays 16 | Hashes 17 | Ranges 18 | Times and Dates* 19 | Flow (incl. logic) 20 | Branches 21 | Loops & Iteration 22 | Exceptions 23 | Fibers* 24 | Threads* 25 | I/O (introduce IO class, general concept) 26 | Files (file-specific I/O) 27 | Directories 28 | Processes & External Commands 29 | Sockets 30 | -------------------------------------------------------------------------------- /spec/chapters/classes_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/classes" do 6 | before(:all) do 7 | @chapter = :classes 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/closures_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/closures" do 6 | before(:all) do 7 | @chapter = :closures 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/flow_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/flow" do 6 | before(:all) do 7 | @chapter = :flow 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/messages_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/messages" do 6 | before(:all) do 7 | @chapter = :messages 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/methods_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/methods" do 6 | before(:all) do 7 | @chapter = :methods 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/modules_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/modules" do 6 | before(:all) do 7 | @chapter = :modules 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/objects_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter' 4 | 5 | describe "/objects" do 6 | before(:all) do 7 | @chapter = :objects 8 | end 9 | 10 | it_should_behave_like 'A chapter' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/programs_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter' 4 | 5 | describe "/programs" do 6 | before(:all) do 7 | @chapter = :programs 8 | end 9 | 10 | it_should_behave_like 'A chapter' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/text_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/text" do 6 | before(:all) do 7 | @chapter = :text 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/chapters/variables_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative '../shared/chapter_with_figures' 4 | 5 | describe "/variables" do 6 | before(:all) do 7 | @chapter = :variables 8 | end 9 | 10 | it_should_behave_like 'A chapter with figures' 11 | end 12 | -------------------------------------------------------------------------------- /spec/index_page_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative './spec_helper' 2 | 3 | require_relative './shared/no_compression' 4 | require_relative './shared/any_page' 5 | require_relative './shared/compression' 6 | 7 | describe "/" do 8 | before(:all) do 9 | @url = BASE_URL 10 | end 11 | 12 | describe " with compression: " do 13 | before(:all) do 14 | @page = ua_gzip.cached_get(@url) 15 | end 16 | 17 | it_should_behave_like 'Any page' 18 | it_should_behave_like 'A compressed page' 19 | end 20 | 21 | describe " without compression: " do 22 | before(:all) do 23 | @page = ua_no_gzip.cached_get(@url) 24 | end 25 | 26 | it_should_behave_like 'Any page' 27 | it_should_behave_like 'An uncompressed page' 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /spec/shared/any_page.rb: -------------------------------------------------------------------------------- 1 | shared_examples_for 'Any page' do 2 | it "should exist" do 3 | @url.should be_a_working_link 4 | end 5 | 6 | it "should have a Content-Type header with UTF-8 as the character set" do 7 | @page.response['content-type'].should =~ /charset=UTF-8/i 8 | end 9 | 10 | it "should have a Content-Language header with 'en-GB' as the value" do 11 | @page.response['content-language'].should == 'en-GB' 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /spec/shared/chapter.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative './compression' 4 | require_relative './no_compression' 5 | require_relative './chapter_page' 6 | 7 | shared_examples_for 'A chapter' do 8 | before(:all) do 9 | @url = BASE_URL + @chapter.to_s 10 | end 11 | 12 | describe " with compression: " do 13 | it_should_behave_like 'A compressed page' 14 | it_should_behave_like 'A chapter page' 15 | end 16 | 17 | describe " without compression: " do 18 | it_should_behave_like 'An uncompressed page' 19 | it_should_behave_like 'A chapter page' 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/shared/chapter_with_figures.rb: -------------------------------------------------------------------------------- 1 | require_relative '../spec_helper' 2 | 3 | require_relative './compression' 4 | require_relative './no_compression' 5 | require_relative './chapter_page' 6 | require_relative './figures' 7 | 8 | shared_examples_for 'A chapter with figures' do 9 | before(:all) do 10 | @url = BASE_URL + @chapter.to_s 11 | end 12 | 13 | describe " with compression: " do 14 | it_should_behave_like 'A compressed page' 15 | it_should_behave_like 'A chapter page' 16 | it_should_behave_like 'A page with figures' 17 | end 18 | 19 | describe " without compression: " do 20 | it_should_behave_like 'An uncompressed page' 21 | it_should_behave_like 'A chapter page' 22 | it_should_behave_like 'A page with figures' 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/shared/compression.rb: -------------------------------------------------------------------------------- 1 | shared_examples_for 'A compressed page' do 2 | 3 | before(:all) do 4 | @page = ua_gzip.cached_get(@url) 5 | end 6 | 7 | it "should have a Content-Encoding header with the value 'gzip'" do 8 | @page.response['content-encoding'].should == 'gzip' 9 | end 10 | 11 | it "should be gzipped" do 12 | raw = open(@url, 'Accept-Encoding' => 'gzip') 13 | body = nil 14 | -> do 15 | body = Zlib::GzipReader.new(raw).read 16 | end.should_not raise_error 17 | body.should =~ /Read Ruby/ 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/shared/figures.rb: -------------------------------------------------------------------------------- 1 | shared_examples_for 'A page with figures' do 2 | it "should contain multiple figures" do 3 | @page.parser.css('figure').size.should > 1 4 | end 5 | 6 | it "should contain multiple code samples" do 7 | @page.parser.css('figure[id]'). 8 | select{|f| f['id'].end_with?('.rb')}. 9 | size.should > 1 10 | end 11 | 12 | it "should link code samples to the corresponding example file" do 13 | @page.parser.css('a').each do |a| 14 | a.css('figure[id]'). 15 | select{|figure| figure['id'].end_with?('.rb')}. 16 | each do |figure| 17 | a['href'].should be_end_with(figure['id']) 18 | end 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/shared/html_page.rb: -------------------------------------------------------------------------------- 1 | require_relative './any_page' 2 | 3 | shared_examples_for 'An HTML page' do 4 | def internal_links 5 | @page.links_with(:href => %r{^(#|/)[^/]}). 6 | map{|u| @url + u.href} 7 | end 8 | 9 | it "should feature the book title" do 10 | @page.body.should =~ /Read Ruby/ 11 | end 12 | 13 | it "should have the book title in <title>" do 14 | @page.title.should =~ /Read Ruby/ 15 | end 16 | 17 | it "should have a Content-Type header with 'text/html' as the value" do 18 | @page.response['content-type'].should =~ %r{^text/html} 19 | end 20 | 21 | it "should have internal links" do 22 | internal_links.should_not be_empty 23 | end 24 | 25 | it "should have no broken internal links" do 26 | internal_links.each do |url| 27 | url.should be_a_working_link 28 | end 29 | end 30 | 31 | it "should be valid HTML5" do 32 | @page.body.should be_html5 33 | end 34 | 35 | it_should_behave_like 'Any page' 36 | end 37 | -------------------------------------------------------------------------------- /spec/shared/no_compression.rb: -------------------------------------------------------------------------------- 1 | shared_examples_for 'An uncompressed page' do 2 | before(:all) do 3 | @page = ua_no_gzip.cached_get(@url) 4 | end 5 | 6 | it "should not have a Content-Encoding header" do 7 | @page.response.should_not have_key('content-encoding') 8 | end 9 | 10 | it "should not be gzipped" do 11 | raw = open(@url) 12 | raw.read.should =~ /Read Ruby/ 13 | raw.rewind 14 | -> do 15 | Zlib::GzipReader.new(raw).read 16 | end.should raise_error(Zlib::Error) 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /spec/shared/uncompressed_html.rb: -------------------------------------------------------------------------------- 1 | require_relative './no_compression' 2 | require_relative './html_page' 3 | 4 | shared_examples_for 'An uncompressed HTML page' do 5 | it_should_behave_like 'An uncompressed page' 6 | it_should_behave_like 'An HTML page' 7 | end 8 | -------------------------------------------------------------------------------- /spec/sitemap_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative './spec_helper' 2 | 3 | describe " /sitemap" do 4 | before(:all) do 5 | @url = BASE_URL + '/sitemap' 6 | @page = ua_gzip.cached_get(@url) 7 | @urls = Nokogiri::XML(@page.body). 8 | search('loc'). 9 | map(&:inner_text). 10 | map{|u| URI.parse(u)}. 11 | uniq 12 | end 13 | 14 | it "should exist" do 15 | @url.should be_a_working_link 16 | end 17 | 18 | it "should contain only working URLs" do 19 | @urls.each do |url| 20 | url.should be_a_working_link 21 | end 22 | end 23 | 24 | it "should link to the root page" do 25 | live_url = BASE_URL.tap{|u| u.host = 'ruby.runpaint.org'} 26 | @urls.should include(live_url) 27 | end 28 | 29 | it "should link to ToC chapters" do 30 | %w{methods messages closures}. 31 | map{|c| BASE_URL + c}. 32 | each do |url| 33 | @urls.should include(url) 34 | end 35 | end 36 | 37 | it "should link to at least 10 URLs" do 38 | @urls.size.should > 10 39 | end 40 | 41 | it "should link to at least 10 .rb files" do 42 | @urls.select{|u| u.path.end_with?('.rb')}.size.should > 10 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /spec/spec.opts: -------------------------------------------------------------------------------- 1 | --color 2 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'rspec/core' 2 | require 'mechanize' 3 | require 'open-uri' 4 | require 'zlib' 5 | 6 | HOST = ENV['READ_RUBY_HOST'] or fail "Set READ_RUBY_HOST" 7 | BASE_URL = URI.parse('http://' + HOST + '/') 8 | 9 | class Mechanize 10 | def visited?(url) 11 | if url.respond_to?(:fragment) 12 | url.fragment = nil 13 | end 14 | ! visited_page(url).nil? 15 | end 16 | 17 | def cached_get(url) 18 | return visited_page(url) if visited?(url) 19 | get(url) 20 | end 21 | end 22 | 23 | def ua_gzip 24 | $ua_gzip ||= Mechanize.new 25 | end 26 | 27 | def ua_no_gzip 28 | $ua_no_gzip ||= Mechanize.new.tap{|m| m.gzip_enabled = false} 29 | end 30 | 31 | Rspec::Matchers.define :be_a_working_link do |expected| 32 | cached_status = ->(url) do 33 | begin 34 | ua_gzip.cached_get(actual).code 35 | rescue Mechanize::ResponseCodeError => e 36 | e.response_code 37 | end.to_i 38 | end 39 | 40 | match do |actual| 41 | cached_status[actual] == 200 42 | end 43 | 44 | failure_message_for_should do |actual| 45 | "expected that #{actual} would be a working link; status code: #{cached_status[actual]}" 46 | end 47 | end 48 | require 'h5-valid/rspec' 49 | -------------------------------------------------------------------------------- /src/examples: -------------------------------------------------------------------------------- 1 | ../examples -------------------------------------------------------------------------------- /src/figures: -------------------------------------------------------------------------------- 1 | ../figures -------------------------------------------------------------------------------- /src/index.xml: -------------------------------------------------------------------------------- 1 | ../book.xml -------------------------------------------------------------------------------- /src/ref/binding.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <appendix version="5.0" 3 | xml:id="ref.binding" xml:lang="en" xmlns="http://docbook.org/ns/docbook" 4 | xmlns:xi="http://www.w3.org/2001/XInclude" 5 | xmlns:xlink="http://www.w3.org/1999/xlink"> 6 | 7 | <title>Binding 8 | 9 | ObjectBinding#evalcodefilenameline Evaluates in the context of the receiver the String of Ruby given as code, returning the result. If filename and/or line are given, they are the filename and line number, respectively, that will be used in error messages generated by code. 10 | -------------------------------------------------------------------------------- /src/ref/class.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Class 8 | 9 | ObjectClass.inheritedclass Hook that is fired when a subclass of the receiver class is created; class is the subclass as a Class object. 10 | 11 | ClassClass.newsuperclass=Object{ } Creates and returns an anonymous class that inherits from superclass. If a block is supplied it is evaluated in the context of this class: within it, self is the new Class instance. 12 | 13 | ObjectClass#allocate Allocates memory for an instance of the receiver’s class, then returns the new object. Invoked automatically by the interpreter when #initialize is called; cannot be overridden. 14 | 15 | ObjectClass#newargument Creates a new instance of the receiver’s class with #allocate, which it initialises with #initialize(argument, …), then returns. 16 | 17 | Class or nilClass#superclass Returns the superclass of the receiver, or nil if the receiver is BasicObject. 18 | -------------------------------------------------------------------------------- /src/ref/exception.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Exception 8 | 9 | ExceptionException.exceptionmessage='Exception' Returns a new Exception with the given message. 10 | 11 | ExceptionException.newmessage='Exception' Returns a new Exception with the given message. 12 | 13 | ArrayException#backtrace Returns the backtrace as an Array of Strings. 14 | 15 | ExceptionException#exceptionmessage Returns the receiver if no argument is given; otherwise, creates a new instance of the receiver’s class with the given message. 16 | 17 | ObjectException#message Returns this Exception’s message. 18 | 19 | ArrayException#set_backtracearray Sets this Exception’s backtrace to the given Array of Strings. 20 | 21 | ObjectException#to_s Returns the message or, if that’s not set, the class name of this Exception. 22 | 23 | -------------------------------------------------------------------------------- /src/ref/falseclass.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | FalseClass 8 | 9 | falseFalseClass#&object Performs a logical AND with the given argument. 10 | 11 | true or falseFalseClass#^object Performs exclusive OR: returns false if object is nil or false; true, otherwise. 12 | 13 | true or falseFalseClass#|object Performs logical OR: returns false if object is nil or false; true, otherwise. 14 | 15 | -------------------------------------------------------------------------------- /src/ref/fiber.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Fiber 8 | 9 | FiberFiber.new{ } Returns a new Fiber whose body is the given block. 10 | 11 | ObjectFiber.yieldargument Suspends the current Fiber, returning control, and any argument(s), to where this Fiber was resumed from. Returns the arguments of the corresponding Fiber#resume call. The root Fiber cannot be yielded from. 12 | 13 | ObjectFiber#resumeargument Resumes this Fiber. If there was a corresponding Fiber.yield, its arguments become this method’s return value, and this method’s arguments become Fiber.yield’s return value. 14 | 15 | -------------------------------------------------------------------------------- /src/ref/marshal.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Marshal 8 | 9 | IO or StringMarshal.dumpobjectiolimit=-1 Serialises object and all of its descendants, writing the result to the IO stream, io, if specified, or returning it as a String. If limit is positive, it specifies the maximum depth of descendant objects to serialise; if it is negative, there is no limit. 10 | 11 | ObjectMarshal.loadsourceproc De-serialises the data in source to a Ruby object. source is either an IO stream from which the data is read, or an object responding to #to_str. If proc is given as a Proc, it is invoked with each object as it is de-serialised. Aliased by Marshal.restore. 12 | 13 | ObjectMarshal.restoresourceproc Aliases Marshal.load. 14 | 15 | -------------------------------------------------------------------------------- /src/ref/object.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Object 8 | 9 | Defines no methods of its own, but mixes in the Kernel Module. 10 | 11 | -------------------------------------------------------------------------------- /src/ref/signal.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Signal 8 | 9 | HashSignal.list Returns a Hash whose keys are signal names, and values the corresponding signal numbers. 10 | 11 | ObjectSignal.trapsignalcommand 12 | ObjectSignal.trapsignal{|signal_number| } Registers a signal handler for the signal identified by signal, where signal is a signal name—as a String or Symbol—or a signal number. If signal is a Proc, or a block is given, they are called with the signal number as their argument. If signal is nil, "", or "IGNORE", the signal is ignored. If signal is "DEFAULT", the operating system’s default handler will be used. If signal is "EXIT", the signal will terminate the interpreter. Returns the previous handler for this signal. 13 | 14 | -------------------------------------------------------------------------------- /src/ref/struct_tms.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Struct::Tms 8 | 9 | FloatStruct::Tms#cstime Returns the number of seconds of system CPU time consumed by waited-for, terminated child processes, i.e. the sum of their Struct::Tms#stime and Struct::Tms#cstime values. Returns 0.0 on Windows. 10 | 11 | FloatStruct::Tms#cutime Returns the number of seconds of user CPU time consumed by waited-for, terminated child processes, i.e. the sum of their Struct::Tms#utime and Struct::Tms#cutime values. Returns 0.0 on Windows. 12 | 13 | FloatStruct::Tms#stime Returns the number of seconds of system CPU time consumed by the calling process. 14 | 15 | FloatStruct::Tms#utime Returns the number of seconds of user CPU time consumed by the calling process. 16 | 17 | -------------------------------------------------------------------------------- /www/.htstatic: -------------------------------------------------------------------------------- 1 | # vim: ft=apache 2 | Options +MultiViews 3 | AddEncoding application/x-gzip .html.gz 4 | # Stop files with .gz extension being served with a Content-Type of 5 | # application/x-gzip 6 | RemoveType .gz 7 | AddCharset utf-8 .html 8 | AddDefaultCharset utf-8 9 | DefaultLanguage en-GB 10 | DirectoryIndex index 11 | ExpiresActive on 12 | ExpiresDefault "access plus 24 hours" 13 | ExpiresByType image/png "access plus 1 years" 14 | ExpiresByType image/css "access plus 1 weeks" 15 | ExpiresByType application/javascript "access plus 1 weeks" 16 | Redirect 301 /text /strings 17 | Redirect 301 /references /bibliography 18 | 19 | Header set Content-Disposition "attachment; filename=read-ruby.pdf" 20 | -------------------------------------------------------------------------------- /www/draft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/www/draft.png -------------------------------------------------------------------------------- /www/examples: -------------------------------------------------------------------------------- 1 | ../examples -------------------------------------------------------------------------------- /www/fonts: -------------------------------------------------------------------------------- 1 | ../fonts/ -------------------------------------------------------------------------------- /www/google18c41b892eabf75d.html: -------------------------------------------------------------------------------- 1 | google-site-verification: google18c41b892eabf75d.html -------------------------------------------------------------------------------- /www/opensearch.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Read Ruby 1.9 Search 4 | Search the contents of the Read Ruby 1.9 ebook 5 | read ruby 1.9 ebook book 6 | runrun@runpaint.org 7 | 8 | UTF-8 9 | UTF-8 10 | 11 | -------------------------------------------------------------------------------- /www/robots.txt: -------------------------------------------------------------------------------- 1 | Sitemap: http://ruby.runpaint.org/sitemap 2 | -------------------------------------------------------------------------------- /www/small-strawberry.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/runpaint/read-ruby/d7869569ba707a01bb53244e66f6f62a5fe96681/www/small-strawberry.jpeg -------------------------------------------------------------------------------- /xsl/callout.xsl: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /xsl/css.xsl: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /xsl/epigraph.xsl: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 17 | 18 |
19 | 20 | 21 |

22 |
23 |
24 | 25 | 26 | 27 |
28 | -------------------------------------------------------------------------------- /xsl/example.xsl: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 16 | 17 |
18 |
19 | 20 | 21 | 22 |
23 |
24 | 25 | 26 |
27 |
28 | 29 | 30 | 31 |
32 |
33 |
34 | -------------------------------------------------------------------------------- /xsl/index.css.xsl: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | section > ol > li > a { 8 | font-weight: bold; 9 | } 10 | 11 | section > ol { 12 | list-style-type: upper-roman; 13 | width: 80%; 14 | } 15 | 16 | li > ol > li { 17 | display: inline; 18 | padding-right: 1%; 19 | } 20 | 21 | li > ol > li:before { 22 | content: "‣"; 23 | } 24 | 25 | li > ol > li:after { 26 | content: " "; 27 | } 28 | 29 | section > h1 { 30 | display: none; 31 | } 32 | 33 | section > p { 34 | text-align: center; 35 | font-weight: bold; 36 | } 37 | 38 | header > p { 39 | margin: 0 10% 0 auto; 40 | } 41 | 42 | header > h1 { 43 | text-align: left; 44 | font-size: 4.5em; 45 | line-height: 90%; 46 | margin: 0; 47 | padding: 0; 48 | } 49 | 50 | header > img { 51 | float: left; 52 | margin-right: 2%; 53 | } 54 | 55 | header > ul > li { 56 | display: inline; 57 | } 58 | 59 | header > ul > li:before { 60 | content: "‣"; 61 | } 62 | 63 | header > ul > li:after { 64 | content: " "; 65 | } 66 | 67 | li > a { 68 | white-space: nowrap; 69 | } 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /xsl/phrasing.xsl: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /xsl/preamble.xsl: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 9 | 10 | 12 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /xsl/search.xsl: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 |
7 | 10 | 11 | 12 |
13 |
14 |
15 | -------------------------------------------------------------------------------- /xsl/sitemap.xsl: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | toc 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | http://ruby.runpaint.org/ 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /xsl/toc.css.xsl: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | article > ol > li > a { font-weight: bold } 8 | ol { 9 | list-style-type: circle; 10 | } 11 | article > ol { 12 | list-style-type: upper-roman; 13 | } 14 | article > ol > li > ol > li { 15 | list-style-type: upper-alpha; 16 | } 17 | article > ol > li > ol > li > ol > li { 18 | list-style-type: decimal; 19 | } 20 | article > ol > li > ol > li > ol > li > ol > li { 21 | list-style-type: lower-alpha; 22 | } 23 | article > ol > li > ol > li > ol > li > ol > li > ol > li { 24 | list-style-type: square; 25 | } 26 | article > ol > li > ol > li > ol > li > ol > li > ol > li > ol > li { 27 | list-style-type: circle; 28 | } 29 | article > ol > li > ol > li > ol > li > ol > li > ol > li > ol > li > ol > li { 30 | list-style-type: disc; 31 | } 32 | ol { 33 | padding-left: 3%; 34 | } 35 | article { 36 | margin-top: 2em; 37 | } 38 | 39 | 40 | 41 | --------------------------------------------------------------------------------