Ruby: How to get the first character of a string
You can use Ruby's open classes to make your code much more readable. For instance, this:
class String
def initial
self[0,1]
end
end
will allow you to use the initial
method on any string. So if you have the following variables:
last_name = "Smith"
first_name = "John"
Then you can get the initials very cleanly and readably:
puts first_name.initial # prints J
puts last_name.initial # prints S
The other method mentioned here doesn't work on Ruby 1.8 (not that you should be using 1.8 anymore anyway!--but when this answer was posted it was still quite common):
puts 'Smith'[0] # prints 83
Of course, if you're not doing it on a regular basis, then defining the method might be overkill, and you could just do it directly:
puts last_name[0,1]
Find the first character in an array string
You could change all of the elements of the array to strings then do what you were originally doing.
string = ["A", "B", 1234, 54321]
string.map { |x| x.to_s }[3].chars.first
=> "5"
Ruby: return the first character from string if it matches and if there is no match then return nil?
Use String#[match_str]
:
If a
match_str
is given, that string is returned if it occurs in the string.Returns
nil
if (...) the match string cannot be found.
'word'['o'] #=> 'o'
'word'['q'] #=> nil
The []
method is very versatile, you can also pass a regular expression or indices in different ways.
Ruby - How to select some characters from string
Try foo[0...100]
, any range will do. Ranges can also go negative. It is well explained in the documentation of Ruby.
ruby/regex getting the first letter of each word
You could simply use split, map and join together here.
string = 'I need help'
result = string.split.map(&:first).join
puts result #=> "Inh"
How do I repeat the first character of words in a string?
You can just split the string by each space, and multiply the first character the number of times you need, then append, or concatenate the "initial" word:
p "abc def".split.map { |word| "#{word[0] * 10}#{word}" }.join(' ')
How to get the first letter of each word
Here is a method I wrote.
def first_chars
final_string = ""
self.split(" ").each do |word|
final_string += word.chr
end
return final_string
end
You would use this instead like "hello world".first_chars
, which would return hw
.
What this does is: splits the given string, self, by spaces into an array. Then it adds the first letter of that word using the .chr
method in the .each
loop, appends that letter to a string that ends up getting returned.
It could be shortened like this:
def first_chars
final_string = ""
self.split(" ").each { |word| final_string += word.chr }
return final_string
end
Ruby: getting character[n] from each element of an array of strings, strictly with array notation
I don't believe there is a way to do what you want, but you could do the following.
str = %w(greater yellow bandicooot).join(' ')
#=> "greater yellow bandicooot"
str.gsub(/(?<=\S)./, '')
#=> "gyb"
The regular expression matches any character that is preceded by a non-whitespace character; that is, it matches all characters other than the first character of the string and characters preceded by a whitespace character.
If one is given the string and there could be multiple spaces between words, one could write:
str.squeeze(' ').gsub(/(?<=\S)./, '')
Related Topics
M Hartl's Ruby on Rails Tutorial Chapter 5 Custom Title on Home Page
What Is Mattr_Accessor in a Rails Module
Ruby: Most Concise Way to Use an Env Variable If It Exists, Otherwise Use Default Value
What's the Opposite of Chr() in Ruby
Rails: Hasmanythroughassociationnotfounderror
Rails Rbenv: Rails: Command Not Found
Why Does Ruby Open-Uri's Open Return a Stringio in My Unit Test, But a Fileio in My Controller
How to Remove All Non - Ascii Characters from a String in Ruby
How to Use Ruby's Readlines.Grep for Utf-16 Files
How to Capitalize the First Letter in a String in Ruby
When We Import CSV Data, How Eliminate "Invalid Byte Sequence in Utf-8"
Error Installing Gem Capybara-Webkit
Rails: Testing Named Scopes with Rspec