简体   繁体   中英

Ruby gem - Highline and downcase?

I have been searching frustratingly for hours and just can not seem to find out how to change the input from the ask function.

input = ask ("Input text: ")

If anybody can help a newbie out that would be amazing!

I've also provided a script link here to the gem below:

ask函数使我可以使用一行字符串来执行此操作。

Just call downcase! (or downcase according to your sitation) on input variable.

Like this,

input = ask("Input text").downcase

Or,

input = ask("Input text")
input.downcase!
p "Downcased: #{input}"

A quick snippet for you

require 'highline'

cli = HighLine.new
input = cli.ask("Input text").downcase!
p "Downcased input: #{input}"

And execution.

$ ruby app.rb 
Input text
LoremIpsum DOlor SIt amet 
"Downcased input: loremipsum dolor sit amet"

If you're new to Ruby and/or reading through the source to understand how a library works, don't worry, I've been there (and after ~10 years in the biz it still happens from time to time).

Depending on what you want to do, marmeladze 's first answer might be what you're looking for.
I think you might be looking for something different (or someone in the future may benefit from an expanded answer), and want to change the case of the answer that Highline captures for validation.


Highline has a #change_case method that will alter the case of the answer, and may be what you're looking for.

input = ask("Do you like cupcakes?") {|q| q.case = :down}

and the result would be exactly the same as the other answer, but accomplish it in a less direct way (because you're manipulating the answer in a block).


However, if you wanted to do something a little more involved and use the change in case as part of your answer validation, then adding .downcase to the end of the ask() block isn't going to cut it.

For example, let's say you want to ask a question and check if the input was y or n . You could do something like:

input = ask("Do you like cupcakes?") do |q|
  q.case = :down
  q.in = ["y","n"]
end

That way input will contain either y or n , and accept inputs of Y , y , N , or n .
You could go even farther by making more changes to the q object (ie something like turning off input echo by using q.echo = false ) inside the block, and use the other features that the HighLine::Question class offers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM