当我运行以下代码时:
cnum = randNum = 0
solutions = []
result = Hash.new
print "What's the number of people playing? "
n = gets.chomp.to_i
while cnum < n
cnum += 1
loop do
randNum = rand(1 .. n)
break unless (solutions.include? randNum) || randNum == cnum
if solutions.include? n = false # If n isn't in the solution
r = rand(1 ... n)
randNum = r
result[result.key(r)] = n
end
end
solutions.push randNum
result[cnum] = randNum
end
result.each do |player, result|
print "Player #{player}, your player is Player #{result}"
gets.chomp
end
我收到以下错误:
gbourdon@Thor-Mint ~/workspace/secretSanta $ ruby code.rb
What's the number of people playing? 5
code.rb:11:in `block in <main>': bad value for range (ArgumentError)
from code.rb:10:in `loop'
from code.rb:10:in `<main>'
但是,当我删除这部分代码时:
if solutions.include? n = false # If n isn't in the solution
r = rand(1 ... n)
randNum = r
result[result.key(r)] = n
end
该程序有效(尽管有一些错误,上面的代码片段的目标是修复)。为什么会这样,我该怎么做才能解决它?另外,为什么只有在添加了代码块时才会出现错误?
答案 0 :(得分:2)
Ruby将此行视为
if solutions.include?(n = false) # If n isn't in the solution
因此,您要将n
分配给false
并检查solutions
是否在n
。如果没有,则再次循环,这次false
仍然等于randNum = rand(1 .. n)
,然后尝试创建一个新范围:
n == false
并且该错误消失了,因为自1
以来,您正在尝试创建从false
到if solutions.include?(n) == false # If n isn't in the solution
的范围,最终导致错误。
你可能想检查
if !solutions.include? n # If n isn't in the solution
或者,更简洁
unless solutions.include? n # If n isn't in the solution
或
<?php
require '../models/connection.php';
session_start();
$user_id = $_SESSION[‘user_id'];
$query=mysql_query( "select post_id from User where user_id=$user_id");
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_assoc($query);
$query = mysql_query("
select text_posts.*,video_posts.*,image_posts.*
from (( text_posts outer
join video_posts on text_posts.post_id= video_posts.post_id)outer
join image_posts on image_posts.post_id= text_posts.post_id)");
$data = array();
echo mysql_num_rows($query);
if (mysql_num_rows($query) > 0)
{
while ($row = mysql_fetch_assoc($query))
{
array_push($data,$row);
}
$response = array(
"code" => 200,
"message" => "Success",
"records" => $data
);
}
else
{
$response = '{"code":204,"message":"No posts"}';
}
} else
{
$response = '{"code":204,"message":"Incorrect userid"}';
}
echo stripslashes(json_encode($response));
?>