Search code examples
arraysruby-on-rails-4destructuring

How to destructure an id out of an array in Rails


I'm getting an array back from redis (trhough a controller for my projects) which I need to destructure in my product view.

Array (showing 2 results, but it can many more): ["project-5", "project-4"]

The numbers (5, 4) are my project id's (@project.id) which I need to subtract to use in a .each do function.

All that I can find for it, are destructure solutions for multiple variables. But here I only have 1 variable.

Can anyone help me out with how I can isolate the product id out of this array?


Solution

  • You can use match method to get the ids with the help of regex. Assuming array consists of your projetcs with id-s 3 and 44 then a one-liner would be:

    2.0.0-p353 :091 > array.map{|el| el.match(/\d+$/)[0]}
      => ["3", "44"] 
    

    If you sure need to use .each do then

    array.each do |el|
      el.match(/\d+$/)[0]
    end
    

    You can also use method gsub with regex to replace everything except the id inside string with an empty string, so only id-part of the string will remain. One-liner for this (array = ["proj3ct-3", "project-1567"]):

    2.0.0-p353 :040 > array.map {|el| el.gsub(/(.*\-)[^\d]*/, "")}
      => ["3", "1567"]
    

    .each do similarly to previous example with match.

    EDIT: If you want the do-block to return the array already in formatted form then you should use bang-method from gsub like this: el.gsub!(/(.*\-)[^\d]*/, "") This will also make changes in elements. Non-bang methods only return changed values without altering them.

    Just in case you don't know and would like to test/analyze your regex then this is a good place to do it- I've been using it for quite a while. Also a good place to recheck some basics is here