your programing

변수가 정의되어 있는지 확인하고 있습니까?

lovepro 2020. 10. 3. 11:26
반응형

변수가 정의되어 있는지 확인하고 있습니까?


Ruby에 변수가 정의되어 있는지 어떻게 확인할 수 있나요? 있습니까 isset타입의 방법은 가능?


defined?키워드 ( documentation )를 사용하십시오 . 항목의 종류 또는 nil존재하지 않는 경우 문자열을 반환 합니다.

>> a = 1
 => 1
>> defined? a
 => "local-variable"
>> defined? b
 => nil
>> defined? nil
 => "nil"
>> defined? String
 => "constant"
>> defined? 1
 => "expression"

skalee는 "nil로 설정된 변수가 초기화된다는 점에 주목할 가치가 있습니다."

>> n = nil  
>> defined? n
 => "local-variable"

존재하는 경우 아무것도하지 않고 존재하지 않는 경우 생성하려는 경우에 유용합니다.

def get_var
  @var ||= SomeClass.new()
end

이렇게하면 새 인스턴스가 한 번만 생성됩니다. 그 후 계속 var를 반환합니다.


위 명령문의 올바른 구문은 다음과 같습니다.

if (defined?(var)).nil? # will now return true or false
 print "var is not defined\n".color(:red)
else
 print "var is defined\n".color(:green)
end

( var)를 변수로 대체 하십시오. 이 구문은 if 문에서 평가를 위해 참 / 거짓 값을 반환합니다.


defined?(your_var)작동합니다. 당신이하는 일에 따라 다음과 같은 것을 할 수도 있습니다.your_var.nil?


"if"대신 "unless"를 시도하십시오.

a = "apple"
# Note that b is not declared
c = nil

unless defined? a
    puts "a is not defined"
end

unless defined? b
    puts "b is not defined"
end

unless defined? c
    puts "c is not defined"
end

사용 defined? YourVariable
하여 간단하게 어리석게 유지 ..;)


여기에 몇 가지 코드가 있지만 로켓 과학은 없지만 충분히 잘 작동합니다.

require 'rubygems'
require 'rainbow'
if defined?(var).nil?  # .nil? is optional but might make for clearer intent.
 print "var is not defined\n".color(:red)
else
 print "car is defined\n".color(:green)
end

분명히 색상 코드는 필요하지 않으며이 장난감 예제에서는 멋진 시각 화일뿐입니다.


경고 다시 : 일반적인 루비 패턴

이것이 핵심 답인 defined?방법입니다. 위에서 받아 들여진 대답은 이것을 완벽하게 보여줍니다.

하지만 파도 밑에 숨어있는 상어가 있습니다 ...

다음과 같은 일반적인 루비 패턴을 고려하십시오.

 def method1
    @x ||= method2
 end

 def method2
    nil
 end

method2항상을 반환합니다 nil. 를 처음 호출 method1하면 @x변수가 설정되지 않으므로 method2실행됩니다. method2설정 @x됩니다 nil. 괜찮습니다. 모두 훌륭합니다. 하지만 두 번째로 전화하면 어떻게됩니까 method1?

Remember @x has already been set to nil. But method2 will still be run again!! If method2 is a costly undertaking this might not be something that you want.

Let the defined? method come to the rescue - with this solution, that particular case is handled - use the following:

  def method1
    return @x if defined? @x
    @x = method2
  end

The devil is in the details: but you can evade that lurking shark with the defined? method.


You can try:

unless defined?(var)
  #ruby code goes here
end
=> true

Because it returns a boolean.


As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean.

But if you absolutely need a boolean. Use !! (bang bang) or "falsy falsy reveals the truth".

› irb
>> a = nil
=> nil
>> defined?(a)
=> "local-variable"
>> defined?(b)
=> nil
>> !!defined?(a)
=> true
>> !!defined?(b)
=> false

Why it doesn't usually pay to coerce:

>> (!!defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red)) == (defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red))
=> true

Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.

>> puts "var is defined? #{!!defined?(a)} vs #{defined?(a)}"
var is defined? true vs local-variable
=> nil

It should be mentioned that using defined to check if a specific field is set in a hash might behave unexpected:

var = {}
if defined? var['unknown']
  puts 'this is unexpected'
end
# will output "this is unexpected"

The syntax is correct here, but defined? var['unknown'] will be evaluated to the string "method", so the if block will be executed

edit: The correct notation for checking if a key exists in a hash would be:

if var.key?('unknown')

Please note the distinction between "defined" and "assigned".

$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"

x is defined even though it is never assigned!


Also, you can check if it's defined while in a string via interpolation, if you code:

puts "Is array1 defined and what type is it? #{defined?(@array1)}"

The system will tell you the type if it is defined. If it is not defined it will just return a warning saying the variable is not initialized.

Hope this helps! :)


defined? is great, but if you are in a Rails environment you can also use try, especially in cases where you want to check a dynamic variable name:

foo = 1
my_foo = "foo"
my_bar = "bar"
try(:foo)        # => 1
try(:bar)        # => nil
try(my_foo)      # => 1
try(my_bar)      # => nil

참고URL : https://stackoverflow.com/questions/288715/checking-if-a-variable-is-defined

반응형