将变量名称作为输入并输出其值-Ruby

时间:2019-05-23 13:39:46

标签: ruby

我想知道是否有Ruby可以执行以下操作:

<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
    $link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
    if (mysqli_connect_error()) {
        die("There was an error connecting to the database");
    }
    if ($_POST['email'] == '') {
        echo "<p>Email address is required.</p>";
    } else if ($_POST['password'] == '') {
        echo "<p>Password is required.</p>";
    } else {
        $query = "SELECT `id` FROM `users` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
        $result = mysqli_query($link, $query);
        if (mysqli_num_rows($result) > 0) {
            echo "<p>That email address has already been taken.</p>";
        } else {
            $query = "INSERT INTO `users` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
            if (mysqli_query($link, $query)) {
                echo "<p>You have been signed up!";
            } else {
                echo "<p>There was a problem signing you up - please try again later.</p>";
            }
        }
}
}
?>

2 个答案:

答案 0 :(得分:5)

似乎您正在寻找instance_variable_get。从文档中:

  

返回给定实例变量的值;如果未设置实例变量,则返回nil。常规实例变量应包括变量名的@部分。如果提供的符号作为实例变量名称无效,则引发NameError异常。字符串参数将转换为符号。

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a)    #=> "cat"
fred.instance_variable_get("@b")   #=> 99

答案 1 :(得分:2)

是的,有。

@my_var = "foo"
instance_variable_get("@my_var")
 => "foo"