Experience Ruby in 20 minutes

Source: Internet
Author: User
1 #! /Usr/bin/ENV Ruby
2
3 class megagreeter
4 attr_accessor: names // sets attributes. Two methods (name, name =) are automatically generated to access the value of @ name.
// What methods does a class provide? Class Name. instance_methods will tell you that if you only want to know the method you have defined, add a false parameter.
5
6 # create the object
7 def initialize (names = "world") // Constructor
8 @ names = names // defines the local variable @ names
9 end
10
11 # Say hi to everybody
12 def say_hi
13 if @ names. nil? // Determine whether @ names is nil
14 puts "" // output
15 elsif @ names. respond_to? ("Each") // determine whether @ names has an each method
16
17 # @ names is a list of some kind, iterate!
18 @ names. Each do | Name | // Loop
19 puts "hello # {name }! "
20 end
21 else
22 puts "hello # {@ names }! "
23 end
24 end
25
26 # Say bye to everybody
27 def say_bye
28 If @ names. nil?
29 puts ""
30 elsif @ names. respond_to? ("Join ")
31 # Join the list elements with commas
32 puts "goodbye # {@ names. Join (", ")}. Come back soon! "
33 else
34 puts "goodbye # {@ names}. Come back soon! "
35 end
36 end
37
38end
39
40
41if _ file _ = $0 // _ file _ name of the currently running script file, $0Is the name of the startup script.
// This allows the code to be called as a database without running the startup code,
The startup code is called when the script is executed.
42 mg = megagreeter. New
43 mg. say_hi
44 mg. say_bye
45
46 # Change name to be "Zeke"
47 mg. Names = "Zeke"
48 mg. say_hi
49 mg. say_bye
50
51 # change the name to an array of names
52 mg. Names = ["Albert", "Brenda", "Charles ",
53 "Dave", "Englebert"]
54 mg. say_hi
55 mg. say_bye
56
57 # change to nil
58 mg. Names = Nil
59 mg. say_hi
60 mg. say_bye
61end
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.