Ruby anatomy: Difference between revisions

From wikinotes
 
Line 1: Line 1:
= Example =
= Example =
<blockquote>
<blockquote>
<source lang="ruby">
#!/usr/bin/env ruby
# mymodule.rb


<syntaxhighlight lang="bash">
myproject/
  lib/
    bar/
      baz.rb
    foo.rb
  Gemfile
</syntaxhighlight>


class MyClass
{{
  def print_hello
| expand
     puts "hello world"
| <code>lib/bar/baz.rb</code>
|
 
<syntaxhighlight lang="ruby">
module Bar
  class Baz
    def initialize(name:)
      @name = name
    end
 
     def say_hi
      puts("hi, #{@name}")
    end
   end
   end
end
end
</syntaxhighlight>
}}
{{
| expand
| <code>lib/foo.rb</code>
|
<syntaxhighlight lang="ruby">
require 'bar/baz'


if __FILE__ == $0
if __FILE__ == $0
  myclass = MyClass.new()
    baz = Bar::Baz.new(name: "alex")
  myclass.print_hello()
    baz.say_hi()
end
end
</source>
</syntaxhighlight>
 
}}
 


<source lang="bash">
<source lang="bash">
ruby mymodule.rb
ruby -I lib lib/foo.rb
</source>
</source>
</blockquote><!-- example -->
</blockquote><!-- example -->

Revision as of 20:24, 13 November 2022

Example

myproject/
  lib/
    bar/
      baz.rb
    foo.rb
  Gemfile

{{ | expand | lib/bar/baz.rb |

module Bar
  class Baz
    def initialize(name:)
      @name = name
    end

    def say_hi
      puts("hi, #{@name}")
    end
  end
end

}}

{{ | expand | lib/foo.rb |

require 'bar/baz'

if __FILE__ == $0
    baz = Bar::Baz.new(name: "alex")
    baz.say_hi()
end

}}


ruby -I lib lib/foo.rb

basics

RUBY_VERSION()       # ruby version
RUBY_PATCHLEVEL()    # ruby patch revision
RUBY_DESCRIPTION()   # ruby version
3.times {puts "hi"}  # loop 3 times

reflection

myclass = MyClass.new()

myclass.methods                   # print all methods
myclass.methods - Object.methods  # print non-object methods
myclass.class                     # type

myclass.__FILE__                               # file class belongs to
instance.method(:method_name).source_location  # file method is defined in (nil means compiled)

MyModule.constants.select {|c| MyModule.const_get(c).is_a? Class}  # list all classes within a namespace

# files module is defined in
$LOADED_FEATURES.select { |file| File.read(file).include?('module Foo') rescue false }

builtins

Keywords/functions/types built in to ruby are defined within the Kernel module.

Find common types/functions like:

  • at_exit
  • open
  • Integer
  • ...

How to read API Docs

Ruby documentation can be difficult to browse.
In order to determine the scope you must browse:

  • class inheritance hierarchy
  • includes/extends
  • parent-hierarchy's includes/extends
  • includes/extends parent hierarchy


Try using ruby pry instead:

  • ls (show methods/attrs by namespace/class)
  • show-source -ld <method> (show docs/sourcecode)