开发者

What is the !! and a few other things in Ruby?

开发者 https://www.devze.com 2023-01-18 09:29 出处:网络
I have be开发者_JAVA百科en digging through some ruby gem code and i came across these and not sure what they means

I have be开发者_JAVA百科en digging through some ruby gem code and i came across these and not sure what they means

def success?
  !!@success
end

def failure?
  !@success
end

cattr_accessor :test_response

and lastly this chunk of code

class_inheritable_accessor :attributes
self.attributes = []

def self.attribute(name, options={})
  top_level_name = name.to_s.split(".").last.underscore
  define_method top_level_name do
    read_attribute name
  end

If you only know one or two thats fine ...i just want to understand them...thanks


!! is a "cast to boolean". ! negates a value, !! negates the negated value. Hence !! turns any value into a boolean.

> 5
=> 5
> !5
=> false
> !!5
=> true
> !!5 == true
=> true


What parts specifically don't you understand in the second part of code?

The methods success? and failure? in the first snippet return boolean values (true/false) in relation to the @success instance attribute.

cattr_accessor creates a read/write class attribute called test_response

Here's a little more information which is also explained better: http://apidock.com/rails/Class/cattr_accessor

0

精彩评论

暂无评论...
验证码 换一张
取 消