Chinaunix

标题: 请问下怎么解释这种用法:if value.is_a?(Hash) [打印本页]

作者: lklkxcxc    时间: 2016-03-27 16:56
标题: 请问下怎么解释这种用法:if value.is_a?(Hash)
if value.is_a?(Hash)
          value
        else
          { 'value'   => value, }
        end

如果单纯if value.is_a?这个我懂,新手见笑了
作者: lklkxcxc    时间: 2016-03-27 23:51
找到出处了
is_a?(class) → true or false click to toggle source
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

module M;    end
class A
  include M
end
class B < A; end
class C < B; end

b = B.new
b.is_a? A          #=> true
b.is_a? B          #=> true
b.is_a? C          #=> false
b.is_a? M          #=> true

b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true
itself → an_object
Returns obj.


作者: rubyish    时间: 2016-03-28 00:06
If it is a hash
    => return It
if it is not a a hash
    => return a hash # key = 'value', value = it
  1. def ifvalueisahash value
  2.     if value.is_a?(Hash)
  3.         value
  4.     else
  5.         { 'value' => value }
  6.     end
  7. end

  8. va1 = { hello: "world" }    # hash
  9. test1 = ifvalueisahash va1
  10. p test1   # return value:  {:hello=>"world"}


  11. va2 = 456   # bushi yige hash
  12. test2 = ifvalueisahash va2
  13. p test2 # return yige hash => {"value"=>456}

复制代码

作者: lklkxcxc    时间: 2016-03-28 11:08
解释还有例子,好师傅




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2