Asked  7 Months ago    Answers:  5   Viewed   36 times

I am so used to work in PHP with multi-dimensional arrays, where I can assign and initialize a hash by

unset($a); // just to show that there is no variable $a
$a['settings']['system']['memory'] = '1 Gb';
$a['settings']['system']['disk space'] = '100 Gb';

Is there a way to do similar thing in Ruby? Or I need to initialize all dimensions first, and then to assign values. Is it possible to define an advanced Hash which will allow to do what I need? How would you do that?


Update

In addition to the solution proposed by Douglas (see below), I have found a thread on the subject, in which Brian Schröäer has proposed an extension for the Hash class:

class AutoHash < Hash
  def initialize(*args)
    super()
    @update, @update_index = args[0][:update], args[0][:update_key] unless args.empty?
  end

  def [](k)
    if self.has_key?k
      super(k)
    else
      AutoHash.new(:update => self, :update_key => k)
    end
  end

  def []=(k, v)
    @update[@update_index] = self if @update and @update_index
    super
  end
end

It allows to solve the problem when a missing hash item is undesirably created when the item value was only requested, e.g. a['key'].


Some additional references

  1. ruby hash autovivification (facets)
  2. http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/
  3. http://www.eecs.harvard.edu/~cduan/technical/ruby/ycombinator.shtml

 Answers

91

Try this:

def hash_with_default_hash
    Hash.new { |hash, key| hash[key] = hash_with_default_hash }
end

a = hash_with_default_hash

If the key doesn't exist, then the result of the block will be used as the default value. In this case, the default value is also a hash which uses hashes as its default values.

Wednesday, March 31, 2021
 
samayo
answered 7 Months ago
33
$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    echo ... $row['name'] ... $row['url'] ...;
}
Wednesday, March 31, 2021
 
Dunc
answered 7 Months ago
51

Well, if you're keys are unique relatively to all levels, you could do:

array_walk_recursive($options, function($value, $key){
  if($value && in_array($key, array('menu_slug', 'page_title', 'option_group', 'core_template')))
    print $value;  
});

:)

But I assume that your real purpose is to wrap this text in HTML strings, so you should use switch instead of my if statement and print whatever you want. If you need to print the stuff in a certain order, use a temporary array to store the output you generate, and print it after you're done.

Saturday, May 29, 2021
 
JakeGR
answered 5 Months ago
69

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);
Saturday, June 12, 2021
 
aurelijusv
answered 5 Months ago
78

If your regex matches only the relevant part, it should be no problem that it replaces the complete match (like preg_replace('/X/', 'Z', $string)).

But if you need the regex to contain parts that should not be replaced, you need to capture them and insert them back:

preg_replace('/(non-replace)X(restofregex)/', '$1Z$2', $string);
Friday, July 30, 2021
 
jenny
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share