Question mark in the beginning of line in Ruby [duplicate] - ruby

This question already has answers here:
What does the unary question mark (?) operator do?
(4 answers)
Closed 2 years ago.
Why when I use a question mark at the beginning of a line it makes it into a String?
For example:
?a
# => "a"
?1
# => "1"
?(
# => "("
?a + "b"
# => "ab"
When I use more than 1 character it raises error:
?ab
# SyntaxError (syntax error, unexpected '?')
Why it happens?

I found the answer in docs:
There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding
?a #=> "a"
?abc #=> SyntaxError
?\n #=> "\n"
?\s #=> " "
?\\ #=> "\\"
?\u{41} #=> "A"
?\C-a #=> "\x01"
?\M-a #=> "\xE1"
?\M-\C-a #=> "\x81"
?\C-\M-a #=> "\x81", same as above
?あ #=> "あ"

Related

RUBY split word to letters and numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I would like to ask you for help. I have keywords in this form "AB10" and I need to split i to "AB" and "10". What is the best way?
Thank you for your help!
One could use String#scan:
def divide_str(s)
s.scan(/\d+|\D+/)
end
divide_str 'AB10' #=> ["AB", "10"]
divide_str 'AB10CD20' #=> ["AB", "10", "CD", "20"]
divide_str '10AB20CD' #=> ["10", "AB", "20", "CD"]
The regular expression /\d+|\D+/ reads, "match one or more (+) digits (\d) or one or more non-digits (\D).
Here is another way, one that does not employ a regular expression.
def divide_str(s)
digits = '0'..'9'
s.each_char.slice_when do |x,y|
digits.cover?(x) ^ digits.cover?(y)
end.map(&:join)
end
divide_str 'AB10' #=> ["AB", "10"]
divide_str 'AB10CD20' #=> ["AB", "10", "CD", "20"]
divide_str '10AB20CD' #=> ["10", "AB", "20", "CD"]
See Enumerable#slice_when, Range#cover?, TrueClass#^ and FalseClass#^.
Use split like so:
my_str.split(/(\d+)/)
To split any string on the boundary between digits and letters, use either of these 2 methods:
Use split with regex in capturing parentheses to include the delimiter, here a stretch of digits, into the resulting array. Remove empty strings (if any) using a combination of reject and empty?:
strings = ['AB10', 'AB10CD20', '10AB20CD']
strings.each do |str|
arr = str.split(/(\d+)/).reject(&:empty?)
puts "'#{str}' => #{arr}"
end
Output:
'AB10' => ["AB", "10"]
'AB10CD20' => ["AB", "10", "CD", "20"]
'10AB20CD' => ["10", "AB", "20", "CD"]
Use split with non-capturing parentheses: (?:PATTERN), positive lookahead (?=PATTERN) and positive lookbehind (?<=PATTERN) regexes to match the letter-digit and digit-letter boundaries:
strings.each do |str|
arr = str.split(/ (?: (?<=[A-Za-z]) (?=\d) ) | (?: (?<=\d) (?=[A-Za-z]) ) /x)
puts "'#{str}' => #{arr}"
end
The two methods give the same output for the cases shown.

What does this in Ruby do? [duplicate]

This question already has answers here:
what is "?" in ruby
(3 answers)
Closed 4 years ago.
I was looking on solution at codewars and found this piece of code.
What does the part "..?z" in Array(char.next..?z) do?
I know that ".." it is for range ie. "a".."z" but idk. what
?z do.
?z is the same as 'z'. It is a single character literal string.
From the Ruby docs:
There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that corresponds to a single codepoint in the script encoding:
?a #=> "a"
?abc #=> SyntaxError
?\n #=> "\n"
?\s #=> " "
?\\ #=> "\\"
?\u{41} #=> "A"
?\C-a #=> "\x01"
?\M-a #=> "\xE1"
?\M-\C-a #=> "\x81"
?\C-\M-a #=> "\x81", same as above
?あ #=> "あ"
? will convert the given character into string,
?z means 'z'
?a means 'a'
?a..?z means 'a'..'z'

String::scan with string argument behave strange

According to documentation, #scan should accept both String and Regexp instances as parameter. But tests show strange behaviour:
▶ cat scantest.rb
#!/usr/bin/ruby
puts '='*10
puts 'foo'.scan '.'
puts '='*10
puts 'foo'.scan /./
puts '='*10
▶ rb scantest.rb
# ⇒ ==========
# ⇒ ==========
# ⇒ f
# ⇒ o
# ⇒ o
# ⇒ ==========
Inside both pry and irb, it doesn't properly scan for a string as well. What am I doing wrong?
With string '.', it scans for literal dots:
'foo'.scan '.'
# => []
'fo.o'.scan '.'
# => ["."]
While with regular expression /./, it matches any characters (except newline):
'foo'.scan /./
# => ["f", "o", "o"]
"foo\nbar".scan /./
# => ["f", "o", "o", "b", "a", "r"]
your scan should have a parameter that match the string you want to scan otherwise it will return empty arrray
My case:
irb(main):039:0> "foo".scan("o")
=> ["o", "o"]
Your case
'foo'.scan '.'
# => []
There is no dot. present on the 'foo' string so scan return empty array

How to get a substring of text?

I have text with length ~700. How do I get only ~30 of its first characters?
If you have your text in your_text variable, you can use:
your_text[0..29]
Use String#slice, also aliased as [].
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
Since you tagged it Rails, you can use truncate:
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate
Example:
truncate(#text, :length => 17)
Excerpt is nice to know too, it lets you display an excerpt of a text Like so:
excerpt('This is an example', 'an', :radius => 5)
# => ...s is an exam...
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt
if you need it in rails you can use first (source code)
'1234567890'.first(5) # => "12345"
there is also last (source code)
'1234567890'.last(2) # => "90"
alternatively check from/to (source code):
"hello".from(1).to(-2) # => "ell"
If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:
your_text.chars.take(30)

ruby double question mark [duplicate]

This question already has answers here:
what is "?" in ruby
(3 answers)
Closed 7 years ago.
I came across this piece of ruby code:
str[-1]==??
What is the double question mark all about? Never seen that before.
Ruby 1.8 has a ?-prefix syntax that turns a character into its ASCII code value. For example, ?a is the ASCII value for the letter a (or 97). The double question mark you see is really just the number 63 (or the ASCII value for ?).
?a # => 97
?b # => 98
?c # => 99
?\n # => 10
?? # => 63
To convert back, you can use the chr method:
97.chr # => "a"
10.chr # => "\n"
63.chr # => "?"
??.chr # => "?"
In Ruby 1.9, the ?a syntax returns the character itself (as does the square bracket syntax on strings):
?? # => "?"
"What?"[-1] # => "?"
As Ryan says, the ? prefix gives you the ASCII value of a character. The reason why this is useful in this context is that when you use the index notation on a string in Ruby 1.8 the ASCII value is returned rather than the character. e.g.
irb(main):009:0> str = 'hello'
=> "hello"
irb(main):010:0> str[-1]
=> 111
so the following wouldn't test if the last character of a string was the letter 'o'
irb(main):011:0> str[-1] == 'o'
=> false
but this would:
irb(main):012:0> str[-1] == ?o
=> true
and (provided you know what the ? does!) this is slightly clearer than
irb(main):013:0> str[-1] == 111
=> true

Resources