Ruby Assegna stringhe Vere e False?
Sei in grado di assegnare stringhe a vero e falso?
ad esempio sto iniziando con un hash:
shopping_list = {
"milk" => false,
"eggs" => false,
"jalapenos" => true
}
puts "Here is your Shopping List:"
shopping_list.each do |key, value|
puts "#{key} - #{value}"
end
Volevo che l'output mettesse "acquistato" per truee "non acquistato" per false.
Risposte
Usa un inline if o un 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
Stampe:
Here is your Shopping List:
milk - not purchased
eggs - not purchased
jalapenos - purchased
Quale operatore usare: operatore ternario ( ?:) o if/then/else/end?
Ho scelto qui if/then/else/end, ma ho elencato entrambe le opzioni come accettabili. È una questione di stile quale scegli.
Alcuni utenti di Stack Overflow Ruby preferiscono utilizzare un normale file if ... then ... else ... end. È più lungo, ma più chiaro e più idiomatico. Vedi, ad esempio, queste risposte:
https://stackoverflow.com/a/2175392/967621
https://stackoverflow.com/a/4253250/967621
Altri utenti di Stack Overflow preferiscono ?:, che è più conciso e chiaro, se ci sei abituato. Si noti inoltre che The Ruby Style Guide concorda:
Preferisci l'operatore ternario (
?:) aiif/then/else/endcostrutti. È più comune e ovviamente più conciso.
# bad
result = if some_condition then something else something_else end
# good
result = some_condition ? something : something_else
Questo ha risposto alla tua domanda?
shopping_list.each do |key, value|
puts "#{key} - #{purchased?(value)}"
end
def purchased?(boolean)
boolean ? 'purchased' : 'not purchased'
end
Volevo che l'output mettesse "acquistato" per vero e "non acquistato" per falso.
In genere inizi con ifun'espressione :
shopping_list.each do |key, value|
if value
puts "#{key} - purchased"
else
puts "#{key} - not purchased"
end
end
Successivamente, puoi provare a rimuovere le parti di codice duplicate.
Sei in grado di assegnare stringhe a vero e falso?
Sembra una mappatura. Puoi usare un altro hash:
states = {
true => 'purchased',
false => 'not purchased'
}
E fai riferimento a quell'hash quando stampi la tua lista della spesa:
shopping_list.each do |key, value|
puts "#{key} - #{states[value]}"
end
Qui, states[value]recupera il valore di uscita per valuedalla stateshash.