development

not_nil에 Ruby 또는 Ruby-ism이 있습니까?

big-blog 2020. 10. 5. 08:15
반응형

not_nil에 Ruby 또는 Ruby-ism이 있습니까? nil의 반대? 방법?


나는 Ruby에 대한 경험이 없기 때문에 내 코드는 관용적이지 않고 "추악"하다고 느낀다.

def logged_in?
  !user.nil?
end

차라리

def logged_in?
  user.not_nil?
end

그러나 반대되는 방법을 찾을 수 없습니다. nil?


ActiveSupport를 사용할 때 user.present? http://api.rubyonrails.org/classes/Object.html#method-i-present%3F 가 있습니다. nil이 아닌지 확인하십시오.

def logged_in?
  user # or !!user if you really want boolean's
end

부울에 지나치게 관심이있는 것 같습니다.

def logged_in?
  user
end

사용자가 nil이면 login_in? "거짓"값을 반환합니다. 그렇지 않으면 객체를 반환합니다. Ruby에서는 JavaScript처럼 "truthy"및 "falsey"값이 있으므로 true 또는 false를 반환 할 필요가 없습니다.

최신 정보

Rails를 사용하는 경우 다음 present?메소드 를 사용하여 더 잘 읽을 수 있습니다 .

def logged_in?
  user.present?
end

질문에 대한 답변으로 제시 present?되는 다른 답변을 조심하십시오 .

present?blank?in rails 의 반대입니다 .

present?의미있는 값이 있는지 확인합니다. 다음은 present?검사에 실패 할 수 있습니다 .

"".present? # false
"    ".present? # false
[].present? # false
false.present? # false
YourActiveRecordModel.where("false = true").present? # false

반면 !nil?검사가 있습니다 :

!"".nil? # true
!"    ".nil? # true
![].nil? # true
!false.nil? # true
!YourActiveRecordModel.where("false = true").nil? # true

nil?개체가 실제로 있는지 확인합니다 nil. 다른 건 : 빈 문자열은 0, false무엇이든 아니다 nil.

present?매우 유용하지만 nil?. 두 가지를 혼동하면 예기치 않은 오류가 발생할 수 있습니다.

귀하의 사용 사례 present?는 작동하지만 항상 차이점을 인식하는 것이 좋습니다.


아마도 이것이 접근 방식 일 수 있습니다.

class Object
  def not_nil?
    !nil?
  end
end

다음을 사용할 수 있습니다.

if object
  p "object exists"
else
  p "object does not exist"
end

이것은 nil뿐만 아니라 false 등에서도 작동하므로 사용 사례에서 작동하는지 테스트해야합니다.


I arrived at this question looking for an object method, so that I could use the Symbol#to_proc shorthand instead of a block; I find arr.find(&:not_nil?) somewhat more readable than arr.find { |e| !e.nil? }.

The method I found is Object#itself. In my usage, I wanted to find the value in a hash for the key name, where in some cases that key was accidentally capitalized as Name. That one-liner is as follows:

# Extract values for several possible keys 
#   and find the first non-nil one
["Name", "name"].map { |k| my_hash[k] }.find(&:itself)

As noted in other answers, this will fail spectacularly in cases where you are testing a boolean.


May I offer the Ruby-esque ! method on the result from the nil? method.

def logged_in?
  user.nil?.!
end

So esoteric that RubyMine IDE will flag it as an error. ;-)

참고URL : https://stackoverflow.com/questions/4012775/is-there-a-ruby-or-ruby-ism-for-not-nil-opposite-of-nil-method

반응형