Ternary expression with "defined?" returns an "expression" instead of a value?

I am new to Ruby and Rails, but even after searching and google I could not find the answer to this question.

I have a simple abbreviated Ruby if statement that should return an integer like this:

 # in the context of this erb document `amount` is defined as 5. @c = ( defined? amount ? amount : r( 1,4 ) ) 

r() is a special helper function that returns a random number between them in this case 1 and 4.

The way I intend to work this out is that if amount defined, then use a number defined as amount , else generates a random number from 1 to 4 and use instead.

When @c however, Ruby exits expression , not numbers.

What do I need to do to get this to work the way I thought, and what am I doing wrong?

Thanks so much for reading!

+6
source share
3 answers

defined? associated with amount ? amount : r(1,4) amount ? amount : r(1,4) , therefore it is equivalent to:

 defined?(amount ? amount : r(1,4)) 

You probably want:

 defined?(amount) ? amount : r(1,4) 

Actually, the probability that amount || r(1,4) amount || r(1,4) or amount.nil? ? r(1,4) : amount amount.nil? ? r(1,4) : amount amount.nil? ? r(1,4) : amount will be better suited to what you want, since I think you don't want this:

  1.9.3p194: 001> defined? (Amount)
  => nil 
 1.9.3p194: 002> amount = nil
  => nil 
 1.9.3p194: 003> defined? (Amount)
  => "local-variable" 

... in this case, @c will be nil - the value of a particular variable.

+8
source

Use the || operator in this case:

 @c = amount || r (1,4) 

defined? method in your code defined? works for amount ? amount : r( 1,4 ) amount ? amount : r( 1,4 ) , not just the amount as you planned. In addition, the operator defined? probably does not do what you expect, look at this blog post to get an idea.

+2
source

You are looking for a zero coalescence operator. Try the following:

 @c = amount || r(1,4) 

This code will assign @c if a quantity is specified. If not, then the result r (1,4) - @c will be assigned.

http://eddiema.ca/2010/07/07/the-null-coalescing-operator-c-ruby-js-python/

+1
source

Source: https://habr.com/ru/post/914999/


All Articles