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
$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.
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()
:
x = "one"
p Array(x) # ["one"]
x = [1]
p Array(x) # [1], not [[1]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.