Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Nil In Ruby

Tags:

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.

like image 282
Vijay Avatar asked Feb 11 '26 03:02

Vijay


2 Answers

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.

like image 159
Marek Lipka Avatar answered Feb 17 '26 04:02

Marek Lipka


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
# => "" 
like image 25
shivam Avatar answered Feb 17 '26 04:02

shivam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!