您是否可以将字符串分配为true和false?
例如,我从哈希开始:
shopping_list = {
"milk" => false,
"eggs" => false,
"jalapenos" => true
}
puts "Here is your Shopping List:"
shopping_list.each do |key, value|
puts "#{key} - #{value}"
end
我希望将true
的输出设置为“已购买”,而将false
的输出设置为“未购买”。
答案 0 :(得分:3)
这是否回答了您的问题?
shopping_list.each do |key, value|
puts "#{key} - #{purchased?(value)}"
end
def purchased?(boolean)
boolean ? 'purchased' : 'not purchased'
end
答案 1 :(得分:2)
使用内联if
或 ternary if operator
:
shopping_list = {
"milk" => false,
"eggs" => false,
"jalapenos" => true
}
puts "Here is your Shopping List:"
shopping_list.each do |key, value|
puts "#{key} - #{if value then 'purchased' else 'not purchased' end}"
# or this:
# puts "#{key} - #{value ? 'purchased' : 'not purchased'}"
end
打印:
Here is your Shopping List:
milk - not purchased
eggs - not purchased
jalapenos - purchased
要使用哪个运算符:三元运算符(?:
)或if/then/else/end
?
我在这里选择if/then/else/end
,但列出了两个可接受的选项。选择哪种样式取决于样式。
某些堆栈溢出Ruby用户更喜欢使用常规的if ... then ... else ... end
。它更长,但更清晰,更惯用。例如,请参见以下答案:
https://stackoverflow.com/a/2175392/967621
https://stackoverflow.com/a/4253250/967621
其他Stack Overflow用户更喜欢?:
,如果您习惯使用?:
,则它更简洁明了。另请注意,The Ruby Style Guide同意:
优先使用
if/then/else/end
构造的三元运算符(# bad result = if some_condition then something else something_else end # good result = some_condition ? something : something_else
)。它更常见,也更简洁。
self::$parsed = preg_replace( '/\|\|([^\^\$=,]+).*/', '*://*.$1/*', $file );
答案 2 :(得分:2)
我希望输出的结果为“购买”为真,而“未购买”为假。
您通常以if
expression开头:
// This is the first Query (works correctly)
@Query(value = "SELECT * FROM accounts WHERE email = ?1", nativeQuery = true)
Account findByEmailAddress(String emailAddress);
// This is the second Query (doesn't work)
@Modifying
@Query(value = "UPDATE accounts SET disabled = 1 WHERE email= ?1 ", nativeQuery = true)
int disableAccountByEmail(String emailAddress);
稍后,您可以尝试删除重复的代码部分。
您是否可以将字符串分配为true和false?
这听起来像是映射。您可以使用其他哈希:
shopping_list.each do |key, value|
if value
puts "#{key} - purchased"
else
puts "#{key} - not purchased"
end
end
并在打印购物清单时引用该哈希值:
states = {
true => 'purchased',
false => 'not purchased'
}
在这里,shopping_list.each do |key, value|
puts "#{key} - #{states[value]}"
end
从states[value]
哈希中获取value
的输出值。