File tree 2 files changed +24
-0
lines changed
2 files changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -9,14 +9,20 @@ describe YAML::Any do
9
9
10
10
it " gets string" do
11
11
YAML .parse(" hello" ).as_s.should eq(" hello" )
12
+ YAML .parse(" hello" ).as_s?.should eq(" hello" )
13
+ YAML .parse(" hello:\n - cruel\n - world\n " ).as_s?.should be_nil
12
14
end
13
15
14
16
it " gets array" do
15
17
YAML .parse(" - foo\n - bar\n " ).as_a.should eq([" foo" , " bar" ])
18
+ YAML .parse(" - foo\n - bar\n " ).as_a?.should eq([" foo" , " bar" ])
19
+ YAML .parse(" hello" ).as_a?.should be_nil
16
20
end
17
21
18
22
it " gets hash" do
19
23
YAML .parse(" foo: bar" ).as_h.should eq({" foo" => " bar" })
24
+ YAML .parse(" foo: bar" ).as_h?.should eq({" foo" => " bar" })
25
+ YAML .parse(" foo: bar" )[" foo" ].as_h?.should be_nil
20
26
end
21
27
end
22
28
Original file line number Diff line number Diff line change @@ -157,18 +157,36 @@ struct YAML::Any
157
157
@raw .as(String )
158
158
end
159
159
160
+ # Checks that the underlying value is `String`, and returns its value.
161
+ # Returns `nil` otherwise.
162
+ def as_s ? : String ?
163
+ as_s if @raw .is_a?(String )
164
+ end
165
+
160
166
# Checks that the underlying value is `Array`, and returns its value.
161
167
# Raises otherwise.
162
168
def as_a : Array (Type )
163
169
@raw .as(Array )
164
170
end
165
171
172
+ # Checks that the underlying value is `Array`, and returns its value.
173
+ # Returns `nil` otherwise.
174
+ def as_a ? : Array (Type )?
175
+ as_a if @raw .is_a?(Array (Type ))
176
+ end
177
+
166
178
# Checks that the underlying value is `Hash`, and returns its value.
167
179
# Raises otherwise.
168
180
def as_h : Hash (Type , Type )
169
181
@raw .as(Hash )
170
182
end
171
183
184
+ # Checks that the underlying value is `Hash`, and returns its value.
185
+ # Returns `nil` otherwise.
186
+ def as_h ? : Hash (Type , Type )?
187
+ as_h if @raw .is_a?(Hash (Type , Type ))
188
+ end
189
+
172
190
# :nodoc:
173
191
def inspect (io )
174
192
@raw .inspect(io)
You can’t perform that action at this time.
0 commit comments