Vijay
Vijay

Reputation: 453

Handling Nil In Ruby

In .Net there is one option for null values like a = a ?? "" + "some string value" This means if a is null take a as "" this. I want to know is there any thing like this in ruby.

Upvotes: 2

Views: 323

Answers (3)

hlcfan
hlcfan

Reputation: 333

In Ruby, if an object could be converted to a String, we can do like "#{nil} some string value"

Here, it takes the nil(or some value) as string.

Upvotes: 1

shivam
shivam

Reputation: 16506

If you want to prepend/append it to a string, best thing to do is:

a.to_s + "some string value"

This will automatically handle even the nil values.

a = nil
a.to_s
# => "" 

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51171

In Ruby, you can do:

a ||= ''

this means that if a is nil or false, empty string would be assigned to it. Note that this is an expression that returns eventual value of a.

Upvotes: 6

Related Questions