-1
row = {"joining_date"=>"18/07/2015", "name"=>" Joe Doe ", "company"=>" Google", "location"=>" New York ", "role"=>"developer", "email"=>"joe@doe.com", "mobile"=>"11-(640)123-45674", "address"=>"4 XYZ Road", "validity"=>"true"}

row is invalid only if any one of the fields(joining_date, name, company, location, email, address) is nil or not present.

def is_valid?
  valid = true
  if row[:name] == nil || row[:joining_date] == nil || row[:address] == nil || row[:email] == nil || row[:company] == nil || row[:location] == nil
    valid = false
  end
  valid 
end

Is there any way that I can simplify and refactor the above method in rails to find it more efficient using regex?

Sri
  • 2,233
  • 4
  • 31
  • 55

1 Answers1

0

Probably, but I wouldn't use a regex as it's in a hash. As you're using rails you can use present? or blank?.

row.values.any?(&:blank?)

Would return true if any are blank

for your case

def is valid?
  row.values.all?(&:present?)
end
j-dexx
  • 10,286
  • 3
  • 23
  • 36
  • Thanks. But I dont want to check for all the keys. It's only specific values should not be blank. – Sri Aug 09 '16 at 10:14
  • 1
    @Vinay then you just slice to just those keys, `row.slice(:key_1, :key_2, :key_3).values.all?(&:present?)` – lusketeer Aug 09 '16 at 10:16
  • @lusketeer row.slice? Undefined method for 'slice' for HASH – Sri Aug 09 '16 at 10:20
  • @Vinay it's a rails method, but if you wanna just do the ruby way, refer to this [post](http://stackoverflow.com/a/30551934/1301840) just simply use [`values_at`](http://apidock.com/ruby/Hash/values_at) – lusketeer Aug 09 '16 at 10:29