你如何在ruby中转换/类型-guggle作为数组?

时间:2022-08-24 07:33:40

In PHP, I'm used to be able to type-juggle easily, for example, take any parameter and cast it as an array like so:

在PHP中,我习惯于能够轻松地键入-guggle,例如,接受任何参数并将其转换为数组,如下所示:

<?php

$foo = [1];
var_dump($foo);
// array(1) {
//   [0]=>
//   int(1)
// }

$foo = 1;
var_dump((array)$foo);
// array(1) {
//   [0]=>
//   int(1)
// }

$foo = "one";
var_dump((array)$foo);
// array(1) {
//   [0]=>
//   string(3) "one"
// }

What is a simple approximation of the same in Ruby? I feel like I am missing something extremely simple in the documentation.

Ruby中对它的简单近似是什么?我觉得我在文档中遗漏了一些非常简单的东西。

1 个解决方案

#1


3  

There is no equivalent. The closest thing would be to simply wrap a variable in an array:

没有等价物。最接近的是简单地将变量包装在数组中:

x = "one"
p [x] # ["one"]

If you want to wrap something in an array unless it's already an array, use Array():

如果要将数据包装在数组中,除非它已经是数组,请使用Array():

x = "one"
p Array(x) # ["one"]

x = [1]
p Array(x) # [1], not [[1]]

#1


3  

There is no equivalent. The closest thing would be to simply wrap a variable in an array:

没有等价物。最接近的是简单地将变量包装在数组中:

x = "one"
p [x] # ["one"]

If you want to wrap something in an array unless it's already an array, use Array():

如果要将数据包装在数组中,除非它已经是数组,请使用Array():

x = "one"
p Array(x) # ["one"]

x = [1]
p Array(x) # [1], not [[1]]