Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Entry point
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Ruby=== In [[Ruby (programming language)|Ruby]], there is no distinct main function. Instead, code written outside of any <code>class .. end</code> or <code>module .. end</code> scope is executed in the context of a special "<code>main</code>" object. This object can be accessed using <code>self</code>: <syntaxhighlight lang="irb"> irb(main):001:0> self => main </syntaxhighlight> It has the following properties: <syntaxhighlight lang="irb"> irb(main):002:0> self.class => Object irb(main):003:0> self.class.ancestors => [Object, Kernel, BasicObject] </syntaxhighlight> Methods defined outside of a <code>class</code> or <code>module</code> scope are defined as private methods of the "<code>main</code>" object. Since the class of "<code>main</code>" is <code>Object</code>, such methods become private methods of almost every object: <syntaxhighlight lang="irb"> irb(main):004:0> def foo irb(main):005:1> 42 irb(main):006:1> end => nil irb(main):007:0> foo => 42 irb(main):008:0> [].foo NoMethodError: private method `foo' called for []:Array from (irb):8 from /usr/bin/irb:12:in `<main>' irb(main):009:0> false.foo NoMethodError: private method `foo' called for false:FalseClass from (irb):9 from /usr/bin/irb:12:in `<main>' </syntaxhighlight> The number and values of command-line arguments can be determined using the <code>ARGV</code> constant array: <syntaxhighlight lang="console"> $ irb /dev/tty foo bar tty(main):001:0> ARGV ARGV => ["foo", "bar"] tty(main):002:0> ARGV.size ARGV.size => 2 </syntaxhighlight> The first element of <code>ARGV</code>, <code>ARGV[0]</code>, contains the first command-line argument, not the name of program executed, as in C. The name of program is available using <code>$0</code> or <code>$PROGRAM_NAME</code>.<ref>[https://docs.ruby-lang.org/en/master/ARGF.html class ARGF] β on Ruby <code>ARGV</code></ref> Similar to Python, one could use: <syntaxhighlight lang="ruby"> if __FILE__ == $PROGRAM_NAME # Put "main" code here end </syntaxhighlight> to execute some code only if its file was specified in the <code>ruby</code> invocation.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)