Лучший способ преобразовать строки в символы в хеше

  <table>
<tr>
    <th>Id</th>
    <th>Name</th>
    <th>Serial</th>
</tr>

<?php


$servername = "localhost";
$username = "";
$password = "";
$dbname = "verify";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$result = $conn->query($sql);

$stack = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        array_push($stack, $row);
        if(!$array) {
            return $row;
        }
    }
}

$conn->close();




foreach($stack as $item)
{
    echo "<tr><td>" . $row['ProductId'] . "</td><td>" . $row['Name'] . "</td>.  <td>" . $row['SerialId'] . "</td></tr>";
}




?>

241
задан Max 30 September 2014 в 03:43
поделиться

6 ответов

Если вам нужен однострочный,

my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

скопирует хеш в новый с символизированными ключами.

220
ответ дан 23 November 2019 в 03:14
поделиться

Would something like the following work?

new_hash = Hash.new
my_hash.each { |k, v| new_hash[k.to_sym] = v }

It'll copy the hash, but you won't care about that most of the time. There's probably a way to do it without copying all the data.

3
ответ дан 23 November 2019 в 03:14
поделиться

You could be lazy, and wrap it in a lambda:

my_hash = YAML.load_file('yml')
my_lamb = lambda { |key| my_hash[key.to_s] }

my_lamb[:a] == my_hash['a'] #=> true

But this would only work for reading from the hash - not writing.

To do that, you could use Hash#merge

my_hash = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(YAML.load_file('yml'))

The init block will convert the keys one time on demand, though if you update the value for the string version of the key after accessing the symbol version, the symbol version won't be updated.

irb> x = { 'a' => 1, 'b' => 2 }
#=> {"a"=>1, "b"=>2}
irb> y = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(x)
#=> {"a"=>1, "b"=>2}
irb> y[:a]  # the key :a doesn't exist for y, so the init block is called
#=> 1
irb> y
#=> {"a"=>1, :a=>1, "b"=>2}
irb> y[:a]  # the key :a now exists for y, so the init block is isn't called
#=> 1
irb> y['a'] = 3
#=> 3
irb> y
#=> {"a"=>3, :a=>1, "b"=>2}

You could also have the init block not update the hash, which would protect you from that kind of error, but you'd still be vulnerable to the opposite - updating the symbol version wouldn't update the string version:

irb> q = { 'c' => 4, 'd' => 5 }
#=> {"c"=>4, "d"=>5}
irb> r = Hash.new { |h,k| h[k.to_s] }.merge(q)
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called
#=> 4
irb> r
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called again, since this key still isn't in r
#=> 4
irb> r[:c] = 7
#=> 7
irb> r
#=> {:c=>7, "c"=>4, "d"=>5}

So the thing to be careful of with these is switching between the two key forms. Stick with one.

4
ответ дан 23 November 2019 в 03:14
поделиться

Вот лучший метод, если вы используете Rails:

params. symbolize_keys

Конец.

Если нет, просто скопируйте их код (он также находится в ссылке):

myhash.keys.each do |key|
  myhash[(key.to_sym rescue key) || key] = myhash.delete(key)
end
303
ответ дан 23 November 2019 в 03:14
поделиться

Мне очень нравится гем Mash .

вы можете сделать mash ['key'] , или mash [: key] , или mash.key

20
ответ дан 23 November 2019 в 03:14
поделиться

Для конкретного случая YAML в Ruby, если ключи начинаются с ': ', они будут автоматически интернированы как символы.

require 'yaml'
require 'pp'
yaml_str = "
connections:
  - host: host1.example.com
    port: 10000
  - host: host2.example.com
    port: 20000
"
yaml_sym = "
:connections:
  - :host: host1.example.com
    :port: 10000
  - :host: host2.example.com
    :port: 20000
"
pp yaml_str = YAML.load(yaml_str)
puts yaml_str.keys.first.class
pp yaml_sym = YAML.load(yaml_sym)
puts yaml_sym.keys.first.class

Вывод:

#  /opt/ruby-1.8.6-p287/bin/ruby ~/test.rb
{"connections"=>
  [{"port"=>10000, "host"=>"host1.example.com"},
   {"port"=>20000, "host"=>"host2.example.com"}]}
String
{:connections=>
  [{:port=>10000, :host=>"host1.example.com"},
   {:port=>20000, :host=>"host2.example.com"}]}
Symbol
112
ответ дан 23 November 2019 в 03:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: