Home>

I have a two-dimensional array with the expression katou is 1 and aoi is 2.
I want to build a program that retrieves the numerical value of the person specified in b
In this case I want to extract 1 as a number

b = "katou"
[["katou", "1"], ["aoi", "2"]]
What I tried and what I wanted to do

I'm searching one by one using a two-dimensional array as a hash, but nil is output.
nil does not want to output
When I output with puts, nil disappears, but it actually exists.
Perhaps the process itself is easier to write? I think

a = [["katou", "1"], ["aoi", "2"]]
 b = "katou"
 2.times do | s |
     c = Hash [* a [s]]
     d = c.invert
     puts d.key (b)
 end
  • Answer # 1

    Is this something like this?

    a = [["katou", 1], ["aoi", 2]]
    b = "katou"
    el = a.find {| x | x [0] == b}
    if el == nil
      p "not found"
    else else
      p el
      p el [1]
    end

  • Answer # 2

    At the time of the second repetitiondIs{"2" =>"aoi"}SobIn other words"katou"The value of does not exist,d.key (b)IsnilWill be.

    Postscript

    I finally understood what I wanted to do by changing the question text. It's just a search.
    I was processing one by one, so I thought I had done something different.

    a = [["katou", "1"], ["aoi", "2"]]
     b = "katou"
    p a.assoc (b)
    # =>["katou", "1"]
    p a.assoc (b) [1]
    # =>"1"
     d = a.to_h
    p d
    # =>{"katou" =>"1", "aoi" =>"2"}
    p d [b]
    # =>"1"

  • Answer # 3

    I wondered how important it is to fit the 2D array data into the mold.

    def restruct_to_person (people)
      people.map do | person |
        Person.new (person)
      end
    end
    def find_id_by_name (people, name)
      people.find {| person | person.name.eql? (name)}
            .id # NOTE: Make a .id call to nil if there is no result
    rescue NoMethodError
      ''''
    end
    class Person
      attr_reader: name,: id
      def initialize (person)
        @name, @id = person
      end
    end
    name = "katou"
    people =
      restruct_to_person ([["katou", "1"], ["aoi", "2"]])
    pp find_id_by_name (people, name) # =>'1'
    pp find_id_by_name (people,'foo') # =>''

    It's about "I would write this", but I hope it helps.

Related articles