Leon's Blogging

Coding blogging for hackers.

Ruby - 有什麼事,就 Ask Ruby 吧!

| Comments

ruby 有趣的事,什麼都可以問它XD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
a = [1,2,3]

#問 a 的方法有哪些
a.methods
#=> [:inspect, :to_s, :to_a, :to_h, :to_ary, :frozen?, :==, :eql?, :hash...]

a.public_methods    #取得實例上public方法
a.protected_methods #取得實例上protected方法
a.private_methods   #取得實例上private方法

a.instance_methods           #可取得類別或模組上定義的非private實例方法
a.public_instance_methods    #可取得類別或模組上定義的public實例方法
a.protected_instance_methods #可取得類別或模組上定義的protected實例方法
a.private_instance_methods   #可取得類別或模組上定義的private實例方法

a.instance_methods(false)
如果呼叫方法時加上false,表示僅取得類別或模組中定義的實例方法,排除繼承或含括而來的實例方法。

a.public_class_method  #取得public的模組或類別方法
a.private_class_method #取得private的模組或類別方法

local_variables    #區域變數清單
global_variables   #全域變數清單
instance_variables #物件的實例變數
class_variables    #類別或模組變數

defined? #知道變數是哪個範圍的變數 local? global?

#問它是否有這個方法
a.respond_to? :to_s
#=> true

#問它的 class 是什麼
a.class
#=> Array

#問爸爸的class 是什麼
Array.superclass  => Object

#直接列出祖宗十八代
Array.ancestors
#=> [Array, JSON::Ext::Generator::GeneratorMethods::Array, Enumerable, Object, ActiveSupport::Dependencies::Loadable, PP::ObjectMixin, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject]

Array.included_modules

#列出所有的 constants
Foo.constants

method

1
2
3
4
5
6
7
8
9
10
11
12
13
ask = 'test'

#用 method 方法取得 `length` 這個方法物件
ask.method(:length)
# => #<Method: String#length>

## 使用 owner 方法取得定義這個方法的類別或模組
ask.method(:length).owner
#=> String

#問 method 的來源
ask.method(:length).source_location
# => nil  Ruby 內建的方法,沒辦法直接取得原始碼的路徑

is_a?

1
2
3
4
5
6
7
8
9
10
11
5.is_a? Integer
#=> true
5.kind_of? Integer
#=> true
#because 5 is a Fixnum and Fixnum is a subclass of Integer
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

5.instance_of? Integer
#=> false
- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

官方文件:

參考文件:

Comments