Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: blank? without Rails

Tags:

ruby

I want to have this test:

if (line.blank?) do_stuff

...but I'm in straight ruby, not rails. What's the accepted idiom for accomplishing the same effect?

I'm doing this for a string, where testing for .empty? is not the same as testing for .blank? (An all whitespace string is not empty, but is blank.)

like image 504
baudot Avatar asked Jul 01 '13 04:07

baudot


People also ask

Is nil blank in Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.

What is empty Ruby?

empty? is a String class method in Ruby which is used to check whether the string length is zero or not. Syntax: str. empty? Parameters: Here, str is the given string which is to be checked. Returns: It returns true if str has a length of zero, otherwise false.

IS NULL check in Ruby?

You can check if an object is nil (null) by calling present? or blank? . @object. present? this will return false if the project is an empty string or nil .

What is .present in Ruby?

Chromium (Cr) metal is present in Ruby as an impurity. Ruby has pink to blood-red colour. It is a gemstone. It is a variety of the mineral corundum (aluminium oxide).


2 Answers

This is possible:

line.to_s.strip.empty?
like image 138
sawa Avatar answered Oct 22 '22 21:10

sawa


blank? is not only defined in String, it's also part of Nil, because it is a two-fold test. It checks to see if a variable is either nil? or empty?/white space.

You can't ask a string if it's nil because it doesn't have a nil? method, but you can ask a Nil if it's nil?.

Active Support has core-extensions available, which let us cherry-pick the needed functionality and include the necessary methods. For blank? you can do:

require 'active_support/core_ext/object/blank'

See the blank? for more information and read the entire document to see what else is available. Using Active Support this way removes the need to load all of AS yet get features that are useful.

like image 28
the Tin Man Avatar answered Oct 22 '22 21:10

the Tin Man