Ruby Assegna stringhe Vere e False?

Sep 02 2020

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

2 TimurShtatland Sep 02 2020 at 16:39

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 ( ?:) ai if/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
3 Spikie Sep 02 2020 at 16:37

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
2 Stefan Sep 02 2020 at 16:43

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.