Spyros
Spyros

Reputation: 48686

Ruby and Rails Simple Question on Expression

Hey there, is there a quick Ruby (or Rails) expression that returns nil if an object does not have a value ?

For instance, if self.name is null in database, it should return nil. If it's a string, it should return it. I'm thinking of unless, but maybe there is something better.

Also, if you have a function like get_profession(type), and type can be "first", "second" or "third", what would be an elegant way of inquiring self.first or self.second or self.third(according to type parameter) and return nil unless self.first(or other type) has a string value ?

As you see, the second question closely relates to the first.

Upvotes: 0

Views: 143

Answers (2)

corroded
corroded

Reputation: 21584

it actually returns nil if there was no value. have you actually tried it yet? if an object doesn't have any value it SHOULD return nil

need to add though that your attribute should have a corresponding column name in the database..otherwise it will be an undefined method call.

e.g.

Company.name < -- should return nil if there's a name column in your companies table but has no value

if you don't have a name column it'll say undefined method name.

It is common and cleaner to just check for a field if you're planning to display it like so:

 <%= @person.profession if @person.profession %>

or the other way around

 <%= @person.profession unless @person.profession.nil? %>

Upvotes: 1

Chirantan
Chirantan

Reputation: 15644

In Ruby, if a variable does not have a value, it is nil by default. To answer your second question, you can use the send method to call your "type" methods. Something like,

def get_profession(type)
  # Making sure correct type is passed.
  raise RuntimeError unless ['first', 'second', 'third'].include?(type.to_s)
  send(type)
end

Send expects a method in a string as parameter, which it calls on the same object. In your case if the response of your "type" method has no value, it would be by default be nil.

Upvotes: 2

Related Questions