Ruby: ignoring zero?

I am trying to parse a bunch of json attributes and assign them a hash. Json has tons of levels:

player[:position]=player["positions"]["primary_position"]["position"]["name"]

The problem I am facing is that any of these levels can be zero, which means I need to write four separate zeros? checks only to extract the value.

I don't need values nil- it would be nice if the array just wrote them like " "or something like that.

Is it possible to disable errors nilfor this particular type? Or should I run all of this through a method rescuethat returns the value I want in the case nil?

+4
source share
3 answers
player[:position]=player["positions"]["primary_position"]["position"]["name"] rescue " "

, "", - .

+1

andand, , .

player[:position] = player.andand["positions"].andand["primary_position"].andand["position"].andand["name"]

. , nil, nil. , , nil.

+4

inject:

path  = %w[positions primary_position position name]
value = path.inject(player) { |h, k| h && h[k] }

h && h[k] , , , Hash, h. , .

Hash, :

class Hash
  def follow_path(*path)
    # You could also path.flatten if you're not expecting Array keys
    path.inject(self) { |h, k| h && h[k] }
  end
end

value = person.follow_path(*%w[positions primary_position position name])

:

private

  def follow_path(h, *path)
    # Assuming you're not using Array keys...
    path.flatten.inject(h) { |h, k| h && h[k] }
  end

:

value = follow_path(person, %w[positions primary_position position name])
+1

Source: https://habr.com/ru/post/1532170/


All Articles